2017-10-16 102 views
1

我试图解除单击事件并单击按钮后单击一次附加另一个单击事件。尝试解除绑定单击事件并附加新事件

<small id="selectall_agriculture" onclick="refineSearch.testing('agriculture')">(select all)</small> 

测试函数运行之后,我想selectAllPropertyTypesInGroup()函数来运行,而是测试函数被调用每次。如果我将onclick事件从小标记中移出并从另一个前端控件触发setGroupHeaderNotAllSelected(),则在setGroupHeaderNotAllSelected()函数中使用$('#selectall_'+ groupName).click()创建的click事件工作。我觉得解除绑定不起作用,因为点击事件被硬编码到小标签中。有什么建议么?

refineSearch.testing = function (groupName) { 
    console.log("Click event from front end running instead of the one binded"); 
    setGroupHeaderNotAllSelected (groupName); 
}; 

var setGroupHeaderNotAllSelected = function (groupName) { 
    $('#selectall_' + groupName).unbind('click'); 
    $('#selectall_' + groupName).click(function() { 
     selectAllPropertyTypesInGroup(groupName); 
     return false; 
    }); 
}; 
+0

变化。点击,进行绑定(“点击”? –

+1

删除'onclick'属性,并用不显眼的JS,而不是附加事件(例如,jQuery的'on()'),然后使用'off()'在添加新事件之前删除当前事件。 –

+0

@RoryMcCrossan我不认为'off()'可以“解除绑定”内联事件处理程序。但是,你可以将'onclick'属性设置为null,这将有效地“解除绑定”。 – gforce301

回答

1

jQuery docunbind方法已过时,使用off代替(click是好的,但你可能look aton方法也)

$('#selectall_' + groupName).off('click').click(function() { 
    selectAllPropertyTypesInGroup(groupName); 
    return false; 
}); 

另外,你需要声明onclick属性设置之间进行选择jQuery绑定。因此,而不是对onclick属性使用,我想通过脚本添加hanlder上应用开始

$('#selectall_agriculture').click(function() { 
    refineSearch.testing('agriculture'); 
});