Javascript &引用$(…)。查找(…)”;在onclick事件处理程序中

Javascript &引用$(…)。查找(…)”;在onclick事件处理程序中,javascript,jquery,Javascript,Jquery,我正在使用此代码对页面内的按钮进行单击处理: $(document).on("click", $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"), function (e) { addItemToDocumentGrid(); $('#removeDocumentFromSection').disable(true).addClass("disabled");

我正在使用此代码对页面内的按钮进行单击处理:

$(document).on("click", $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"), function (e) {
        addItemToDocumentGrid();
        $('#removeDocumentFromSection').disable(true).addClass("disabled");
        $('#removeSelection').disable(true).addClass("disabled");
});
但只要我单击页面中的任何位置,事件就会触发。即使它不是我想用
$(“#”+GlobalVariables.currentUserType.find(“.addDocumentToSection”)
选择的假定按钮

$(“#”+GlobalVariables.currentUserType).find(“.addDocumentToSection”)
返回一个元素,该元素实际上是我要选择的按钮


为什么会这样呢?

您正在将onClick事件附加到
文档
元素。尝试:

var button = $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection");
button.on("click", function() {
    addItemToDocumentGrid();
    $('#removeDocumentFromSection').disable(true).addClass("disabled");
    $('#removeSelection').disable(true).addClass("disabled");
});

如果要使用事件委派,第二个参数应该是选择器,而不是jQuery对象

$(document).on("click", '#' + GlobalVariables.currentUserType + " .addDocumentToSection", function (e) {
// ---------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        addItemToDocumentGrid();
        $('#removeDocumentFromSection').disable(true).addClass("disabled");
        $('#removeSelection').disable(true).addClass("disabled");
});
如果不想使用事件委派,则需要对要挂接事件的元素调用
on

$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function (e) {
        addItemToDocumentGrid();
        $('#removeDocumentFromSection').disable(true).addClass("disabled");
        $('#removeSelection').disable(true).addClass("disabled");
});
这一切都包括在我的报告中


jQuery可以在
之前使用选择器。在(“单击”
)上,这应该适合您。

对此的否决票似乎很苛刻。我们不知道OP想要使用事件委派,OP说选择器确实找到了相关的元素;鉴于此,这说明了什么是错误的以及如何修复它。向上投票以平衡:考虑到
$()。find()
正在运行,似乎不需要事件委派就可以给出这个答案,这是合理的。@T–nNguỹn:或者人们阅读速度很快。如果这样,如果你熟悉这些概念,阅读上面的内容不会超过10-15秒。@T–nNguỹn也同样可能:人们阅读问题,看到明显的答案,去添加答案,得到n注意到已经添加了答案,请确保答案与他们将要添加的内容完全一致,请进行投票,而不是添加副本
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function(e){

});