开发者

jQuery - using selector scope as function parameter to bind events

I am applying some click events to all anchors in a grid.

I have some ajax which updates a row in the grid.

开发者_如何学运维

Rather than applying the events to the whole grid again, i wish to just apply to the ajax-updated row, so I pass in the scope to the bind function:

function bindEvents(scope)
{
 scope.find("a").click(function() { //do something });
}

function gridLoad()
{
 ..
 bindEvents($);
}

function ajax()
{
 ..
 bindEvents($(tr));
}

I am getting errors complaining about object doesnt support click event.

This was deffo working when the code was simply

$("a").click(function() { //do something });

also, adding a .each after the find has had no effect.

Is there best practice for this?


Use .live() or .delegate() and you won't need to rebind the handler. It's more efficient than binding a handler for every <a> as well, since there's just a single event listener higher up the DOM tree.

Live: Attach a handler to the event for all elements which match the current selector, now and in the future.

Delegate: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

Just once, on document ready, like this:

$('#grid-id a').live('click', function ()
{
    // do something
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜