每当用户单击#postComment 链接时,我都必须提交评论。
现在有了这段代码,第一次评论提交成功,但第二次提交失败。我认为这是因为 jquery 不正确,它在这里变得困惑 $('.comment a')。
现在我想知道如何使用“this”关键字或任何其他可能的解决方案来访问这些类型的变量。
每次提交评论时,newCommentBox 变量都会附加到 commentWrapper 以生成新的评论框。
J查询:
$('.comment a').click(function(){
comment="<pre>"+$('textarea').val()+"</pre>";
newcommentBox="<div class='CommentBox'>"
+"<div class='dp'><img src='../Images/defaultPic.jpg' width='50' height='50' /></div>"
+"<div class='name'>Muazzam Ali</div>"
+"<div class='comment'>"
+"<textarea cols='70' rows='10'></textarea><br />"
+"<a href='javascript:void(0)' id='postComment'><img src='../Images/commentbutton.png' height='30' width='90' /></a>"
+"</div>"
+"</div>";
$(this).prev().html("");
$(this).hide();
$(this).parent().html(comment);
$('#CommentWrapper').append(newcommentBox);
});
HTML:
<div id="CommentWrapper">
<div id="CommentHeading">Comments:</div>
<div class="CommentBox">
<div class="dp"><img src="../Images/defaultPic.jpg" width="50" height="50" /></div>
<div class="name">Muazzam Ali</div>
<div class="comment">Comment</div>
</div>
<div class="CommentBox">
<div class="dp"><img src="../Images/defaultPic.jpg" width="50" height="50" /></div>
<div class="name">Muazzam Ali</div>
<div class="comment">
<textarea cols="70" rows="10"></textarea><br />
<a href="javascript:void(0)" id="postComment"><img src="../Images/commentbutton.png" height="30" width="90" /></a>
</div>
</div>
</div>
最佳答案
它没有第二次添加评论,因为您还没有将 click
事件处理程序添加到表示提交评论按钮的新 a
元素。实际上,您必须再次向这个新创建的元素添加事件处理程序。或者,使用 jQuery 的委托(delegate)功能,使用 on
方法,将事件处理程序始终添加到您的 a
元素。
不过,就我个人而言,这是我会做的。这是更新后的 JavaScript:
$('.comment a').click(function _this (){
comment = "<pre>"+$('textarea').val()+"</pre>";
newcommentBox = "<div class='CommentBox'>"
+"<div class='dp'><img src='../Images/defaultPic.jpg' width='50' height='50' /></div>"
+"<div class='name'>Muazzam Ali</div>"
+"<div class='comment'>"
+"<textarea cols='70' rows='10'></textarea><br />"
+"<a href='javascript:void(0)' id='postComment'><img src='../Images/commentbutton.png' height='30' width='90' /></a>"
+"</div>"
+"</div>";
$(this).prev().html("");
$(this).hide();
$(this).parent().html(comment);
$('#CommentWrapper').append(newcommentBox);
$('#CommentWrapper').find(".comment a").click(_this);
});
我在这里所做的是将您传递给 $(".comment a").click()
的函数表达式命名为 _this
。我为函数指定的这个名称仅在函数本身内部可用。任何时候发表评论,它都会将自己附加为 next a
元素的点击事件处理程序。它还可以让您避免使用事件委托(delegate),这可能会导致性能下降。 (如果你关心那种事情。)
关于Jquery 使用 this 关键字选择一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10557721/