" $(...)找到(...)"在onclick-eventhandler中

时间:2016-11-25 14:54:06

标签: javascript jquery

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

$(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")返回一个实际上是我想要选择的按钮的元素。

为什么它会像那样?

3 个答案:

答案 0 :(得分:7)

如果要使用事件委托,第二个参数应该是选择器,而不是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");
});

the on documentation已涵盖这一点。

答案 1 :(得分:0)

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

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

答案 2 :(得分:-1)

$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function(e){

});

jQuery可以在.on("click"之前使用选择器,这应该适合你。