我们说我有一个模板,我想循环创建div。我想听一下这些div中包含的按钮的点击次数:
<div class="repeatedDiv">
<button class="reply-button">
</div>
$('.reply-button').on('click',function(e)...)
我想制作特定于其所选div的回复按钮功能。有类似的东西会不会很糟糕:
<div class="repeatedDiv">
<button class="reply-button" id="reply-{{this.id}}">
</div>
答案 0 :(得分:0)
不要让它变得比实际更复杂
$(document).on('click', '.reply-button', function(e){
var divClicked = $(e.target).closest('.repeatedDiv');
// do something with clicked div
// var divClicked is the div elmt that contains the button that was clicked
// doing it this way you might not even need an id at all
console.log(divClicked.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="repeatedDiv">
<button class="reply-button">div1</button>
</div>
<div id="div2" class="repeatedDiv">
<button class="reply-button">div2</button>
</div>
<div id="div3" class="repeatedDiv">
<button class="reply-button">div3</button>
</div>
如果在创建新div时确实需要id,请使用例如动态创建它。
var newID = "id-" + Date.now();
console.log(newID);