如何使用JQuery删除“ onclick”,以便以后可以再次添加?

时间:2019-02-25 21:12:05

标签: javascript jquery

Js代码:

我向某个元素添加了.on(“ click”,...)。

$("#sq" + nextPossibleIndices[i]).on("click", function () {...});

然后我使用.unbind('click')删除它。

$("#sq" + nextPossibleIndices[i]).unbind('click');

因此,先添加然后删除它可以正常工作,但是一旦删除,就无法再次添加到该特定的html元素。

3 个答案:

答案 0 :(得分:0)

您总是可以自己保持状态,就像这样(我已将unbind替换为off,因为unbind已过时):

// Maintain the click handlers in an array.
const clickHandlers = [];

// Add the relevant click handlers:
clickHandlers.push(function(ev) {
  console.log('Do something on click');
});

// Later, set them:
$("#sq" + nextPossibleIndices[handlerIndex]).on(clickHandlers[handlerIndex]);

// Remove them:
$("#sq" + nextPossibleIndices[handlerIndex]).off(clickHandlers[handlerIndex]);

// Then, add them again:
$("#sq" + nextPossibleIndices[handlerIndex]).on(clickHandlers[handlerIndex]);

答案 1 :(得分:0)

我认为您可能正在寻找.off() method,它在不久前被弃用后已取代unbind。在您的代码中,它看起来像这样:

$("#sq" + nextPossibleIndices[i]).off('click');

如果遇到无法正常运行的困难,请尝试再次检查您是否选择了正确的元素。您可以通过在Chrome / Firefox控制台中尝试该方法并从所有内容中删除点击绑定来确认至少该方法(off)有效:$('*').off('click');您不想在实际的网站代码中使用该方法,当然。

答案 2 :(得分:-5)

尝试这种机制

要删除onclick事件

$("#sq" + nextPossibleIndices[i]).removeAttr("onclick");

它将删除onclick属性

相关问题