我有这个javascript代码可以使用这个HTML代码
<span "id="comment'.$id.'">Comment</span>
$id
是不同的数字,例如(1,2,3,4)
HTML代码
<span "id="comment1">Comment</span>
<span "id="comment2">Comment</span>
<span "id="comment3">Comment</span>
JavaScript代码
$('[id^=comment]').click(function() {
this.insertAdjacentHTML("afterend", '\
<div class="cmt-container" >\
<div class="new-com-bt">\
<span >Write a comment ...</span>\
</div>\
<div class="new-com-cnt">\
<textarea class="the-new-com"></textarea>\
<div class="bt-add-com">Post comment</div>\
<div class="bt-cancel-com">Cancel</div>\
</div>\
<div class="clear"></div>\
</div>'
);
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "/",
data: 'act=add-com&id_post='+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
});
我想要做的是当comment1点击代码仅适用于comment1
答案 0 :(得分:0)
使用 var child = $('[id^=comment]')
,您可以选择与该选择器匹配的所有元素。要仅选择触发特定事件的元素,您必须使用:
var child = $(e.target);
或更简单:
var child = $(this);
<强>请注意:强>
在您的情况下,无论您使用什么,都会收到错误,因为 insertAdjacentHTML
不是jQuery方法,而是本机JavaScript方法。因此,您只需使用 this
或 e.target
。
完整代码:
/* ----- JavaScript ----- */
$('[id^=comment]').click(function() {
this.insertAdjacentHTML("afterend", '\
<div class="cmt-container" >\
<div class="new-com-bt">\
<span >Write a comment ...</span>\
</div>\
<div class="new-com-cnt">\
<textarea class="the-new-com"></textarea>\
<div class="bt-add-com">Post comment</div>\
<div class="bt-cancel-com">Cancel</div>\
</div>\
<div class="clear"></div>\
</div>'
);
});
<!----- HTML ----->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<span id="comment1">Comment</span>
<span id="comment2">Comment</span>
<span id="comment3">Comment</span>