[英]JavaScript/jQuery How to do .click function properly?
I have some buttons generated dynamically based on form inputs selected: 我有一些基于所选表单输入动态生成的按钮:
$.each(fields, function (i, field) {
var field_id = $('[name=' + field.name + ']').closest("fieldset").attr('id');
$("#results").append('<button id="jumpToThisStep" data-id="'+field_id.replace('q','')+'">'+field.value+ ' ' +'</button>');
});
} }
In my doc.ready
function I have the following: 在我的
doc.ready
函数中,我具有以下内容:
$('#jumpToThisStep').click(function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});
HTML: HTML:
<button id="jumpToThisStep" data-id="0"> ... </button>
<button id="jumpToThisStep" data-id="1"> ... </button>
<button id="jumpToThisStep" data-id="2"> ... </button>
Upon inspecting the elements they all have the proper data-id
binding. 在检查元素时,它们都具有正确的
data-id
绑定。 But the only one that fires is the first one. 但是唯一触发的是第一个。 What is preventing the others from preforming their
.click
? 是什么让其他人无法执行他们的
.click
?
You need to use event delegation here since your buttons are added dynamically so event delegation will help you to attach the click event to these newly created button: 您需要在此处使用事件委托 ,因为您的按钮是动态添加的,因此事件委托将帮助您将click事件附加到这些新创建的按钮上:
$('#results').on('click', '.jumpToThisStep', function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});
Also id
is unique, you need to use class for your button instead. 另外
id
是唯一的,您需要使用class作为按钮。
HTML DOM id
must be unique. HTML DOM
id
必须是唯一的。 use class
instead of. 使用
class
代替。
<button class="jumpToThisStep" data-id="0"> ... </button>
<button class="jumpToThisStep" data-id="1"> ... </button>
<button class="jumpToThisStep" data-id="2"> ... </button>
If you want to bind event on DOM which you add to document after document ready event, must to use event delegation
. 如果要在文档就绪事件后添加到文档的DOM上绑定事件,则必须使用
event delegation
。
$('#results').on('click', '.jumpToThisStep',function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.