【问题标题】:Jquery on event not firing for buttonsJquery on event 不触发按钮
【发布时间】: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


【解决方案1】:

以下说法是错误的:

componentList.on("click", "#" + id, function () {...

jQuery 足够聪明,只需使用类甚至标签作为第二个参数,就可以知道点击了哪个按钮。

$('.list').on("click", '.btn', function(e) {

Demo中评论的细节

演示

/* 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);
}
<ol class='list'></ol>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • id是防止函数被每个组件调用所必需的,我知道jquery可以解析html但是我不喜欢和js混合
  • @user7951676 无论如何都会调用它,componentList 是 id 的列表,.btn。如果你想避免搜索 DOM 的微不足道的增加,那么使用 id 作为选择器。无论如何,除了解析 HTML,您的问题是让动态创建的元素上的事件起作用。 on('click'... 有效吗?
  • 李。 on 也不起作用,没有 id,每个组件都会调用处理程序,因为事件将匹配每个组件
  • @user7951676 那你不知道什么是事件委托,事件处理程序通过这个找到id 再说了,你怎么能说它不起作用?当你按下一个按钮......你看到它做什么?
  • 当我按下按钮时,无论是我的还是你的答案都没有发生
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多