ActionLink executing multiple times

2019-09-06 10:53发布

问题:

I have an ajax action link which is appending a partial to a div.

$('#hypNewCriteria').click(newClick);
...
var newClick = (function ()
{
    console.log('newClick');
    $.ajax(this.href, {
        success: function (result)
        {
            ...
        }
}

On the first page load and on every partial that is returned I am (probably unnecessarily), am executing via a document.ready

$('#hypNewCriteria').click(newClick);

... subsequent clicks on the actionlink; the number of partial views returned increases by 1 each time. After 7 clicks, it returns 8 partials. I expect only 1 partial to append.

I suspect the .click(newClick) event is appending. Is there a way to set just one click event or clear the event before I set another?

回答1:

You can use jQuery's unbind() method to unbind events.

http://api.jquery.com/unbind/

I would also look into the live() jQuery method. This binds an event to all current and future elements that are added to a page, useful for pages that load partials or add items that require events to be added all the time.



回答2:

Try .one():

$('#hypNewCriteria').one('click', newClick);