In Twitter Bootstrap, how do I unbind an event fro

2020-06-01 01:33发布

I have a function that is bound to the action of hiding a modal dialog.

I'm using code similar to the accepted answer to this question.

$('#myModal').on('hidden', function () {
    // do something…
})

However, this dialog may get reopened for editing, and, when that happens, I don't necessarily want to run this code. Is there a way to "unbind" the function so that it is no longer run when the dialog closes? I haven't found anything in the documentation.

2条回答
乱世女痞
2楼-- · 2020-06-01 01:48

You can do something like to unbind all events tied to the modal element:

Unbind all events in the modal:

/* First option */
$('#myModal').on('hidden', function (e) {
    $(e.currentTarget).unbind(); // or $(this)        
});

/* Second option is to call it directly when needed */
$('#myModal').unbind();

The Bootrap modal also have specific events tied to it, so you can also specify which event(s) you want to unbind.

/* Events are 'hidden', 'hide', 'show', 'shown' */
$('#myModal').unbind(/* specific event here */);

If you wish to remove events tied to the content of the modal, you can simply just empty the elements within $('#myModal').empty() and unbind those elements appropriately.

查看更多
欢心
3楼-- · 2020-06-01 01:51

Use:

$('#myModal').off('hidden');

Why not unbind?

As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

Source: jQuery API.

查看更多
登录 后发表回答