我已经为此寻找答案,我理解事件委托的工作原理,但我什么都不做尝试。 动态创建的按钮在手动点击时不会触发on事件,但是使用trigger()方法有效,我的代码出了什么问题?
components.forEach(function (component) {
var id = randomId();
var li = $.create("li").addClass("col-12");
componentList.append(li);
var btn = $.create("button")
.text(component.type)
.attr("id", id)
.addClass("btn")
.appendTo(li);
componentList.on("click", "#" + id, function () {
alert("test");
window.circuit.push(component.create());
circuitList.refresh();
});
btn.trigger("click");
});
$.create = function (arg) {
return $(document.createElement(arg));
}
randomId = function () {
return "id" + Math.floor(Math.random() * 100000) + "_" + Math.floor(Math.random() * 100000);
}
显示如预期,按钮不会手动触发。 组件是具有type属性和create方法的对象数组。
答案 0 :(得分:0)
以下陈述是错误的:
componentList.on("click", "#" + id, function () {...
jQuery非常聪明,只需使用类或甚至标记作为第二个参数即可知道单击了哪个按钮。
$('.list').on("click", '.btn', function(e) {
在演示中评论的详细信息
/* Had no idea what components is supposed to be */
var components = ['potentiometer', 'transistor', 'capicitor', 'transformer'];
/* On each loop $.map() will run a function */
$.map(components, function(cmp, idx) {
var ranID = randomId();
/* Creating nodes is easy with jQuery
|| You can actually assign a string to a
|| jQuery object and when used with a jQuery method
|| it would be parsed into real HTML
*/
var li = $('<li class="col-12"></li>');
$('.list').append(li);
/* This string is a Template Literal. a TL is a
|| string with a powerful syntax.
*/
var btn = $(`<button id='${ranID}' class='btn' type='button'>${cmp}</button>`);
btn.appendTo(li);
});
/* Originally the OP has a dynamically generated
|| id as the 'this', that's wrong and pointless.
|| That second parameter should be a class ex. '.btn'
*/
$('.list').on("click", '.btn', function(e) {
var ID = $(this)[0].id;
$(`<label for="${ID}"> ${ID}</label>`).insertAfter($(this));
console.log(ID);
alert(`ID:${ID} Type: ${this.textContent}`);
});
function randomId() {
return "id" + Math.floor(Math.random() * 100000) + "_" + Math.floor(Math.random() * 100000);
}
&#13;
<ol class='list'></ol>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;