Javascript 查找后单击元素的jquery

Javascript 查找后单击元素的jquery,javascript,jquery,Javascript,Jquery,为什么我不能将变量作为选择器写入“on”处理程序。你怎么会是对的 var buttons = $('.sector').find('button'); $(document).on('click', buttons, function() { // here buttons not found //... }) $(document).on('click', '.sector button', function() { // here works //... }) 内容可以在

为什么我不能将变量作为选择器写入“on”处理程序。你怎么会是对的

var buttons = $('.sector').find('button');
$(document).on('click', buttons, function() { // here buttons not found
    //...
})

$(document).on('click', '.sector button', function() { // here works
    //...
})

内容可以在ajax请求之后,所以我需要写$(文档)而不是$(按钮)

您可以将其绑定到通过ajax更新内容的div父级

$('#ParentDivOfUpdateId').on('click', '.sector button', function() { 
    // here ParentDivOfUpdateId is Id of div which is parent to your dynamic content
    //...
})

我认为on()背后的基本思想是在动态元素上绑定事件。。。为什么要在之前找到它。因为
.on()
就是这样工作的。如果将选择器作为第二个参数传递,则它必须是字符串。您的
buttons
变量将引用一个jQuery对象,该对象包含行运行时
.sector
中存在的所有按钮元素-它不包括ajax请求后添加的未来元素。Dodgy但
var buttons='.sector button'。您的最佳选择是
$(文档)。在('click','.sector button',function(){…})