【发布时间】:2017-12-20 05:06:53
【问题描述】:
我已经为此寻找了答案,并且我了解事件委托的工作原理,但我尝试过的一切都没有改变。 动态创建的按钮在手动单击时不会触发 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);
}
显示如预期,按钮不会手动触发。 组件是具有类型属性和创建方法的对象数组。
【问题讨论】:
-
你应该尝试使用
$('body').on('click', '#'+id, function() {。 -
将
componentList.on(...)更改为componentList.live(...) -
Live 已被弃用,更改为 body 会产生相同的行为
-
在对象和属性之间放置空格是一种非常烦人的编码习惯。 jQuery 顺便使用了
$.each()。 -
通常我在任何地方都没有空间,因为我使用屏幕阅读器,所以这对我来说很重要,但我被告知要多使用空间,哈哈
标签: javascript jquery event-delegation