如何在jQuery中发布?

Man*_*noz -1 jquery textarea

我在使用这个非常简单的jQuery代码时遇到了麻烦.

我有一个textarea和一个发表评论的按钮.每当我发表评论时,textarea的价值将被列出.

HTML

 <textarea rows="5" cols="40" class="Textarea"></textarea>
<ul>
    <li class="comment_list"></li></ul>    
<input type="button"  value="Post" class="button_post"/>
Run Code Online (Sandbox Code Playgroud)

我正在使用这个jQuery代码 -

$(function(){

var text_t=$(".Textarea").val();
$(".button_post").click(function(){
$(" .comment_list").val(text_t);

});
});
Run Code Online (Sandbox Code Playgroud)

小提琴

Spo*_*key 5

$(function () {
    $(".button_post").click(function () {
        var text_t = $(".Textarea").val(); 
        // text_t has to be in the click function it order for it to update with the new content when you click post (otherwise it will be empty like the textbox was when the page loaded)
        $(".comment_list").text(text_t); // li does not have a value, use html() or text()
    });
});
Run Code Online (Sandbox Code Playgroud)

小提琴


更多细节

$(function(){
var text_t=$(".Textarea").val();
Run Code Online (Sandbox Code Playgroud)

首先执行上述操作将加载textbox文档准备就绪时的值,因此text_t在您的情况下将为空(文本框在页面加载时没有值)

$(".button_post").click(function(){
   $(".comment_list").val(text_t);
});
Run Code Online (Sandbox Code Playgroud)

第二个问题来到这里,li没有值属性,所以你不能使用.val().您可以使用的是.text()(将在html结构之间插入文本<li></li>,或者.html()为html结构插入文本).

请注意,由于text_r在click函数之外,因此单击post时它不会更新为新的文本框值.

}); // end 
Run Code Online (Sandbox Code Playgroud)