开发者

Add an event listener to an object that is added to the DOM via AJAX

I've got a set of checkboxes that are added to a document via an Ajax call

<input type='checkbox' checked class='import'>
<input type='checkbox' checked class='import'>
<input type='checkbox' checked class='import'>
<input type='checkbox' checked class='import'>
<input type='checkbox' checked class='import'>

I've got a few bits of javascript (using prototype)

function check_toggle(obj, e) {
    if   (e.shiftKey)   {obj.checked=!obj.checked;}
    else if (e.altKey)  {obj.checked=true;}
    else if (e.ctrlKey)    {obj.checked=false;}
}
$$('.import').each(function(obj){
    Event.observe(obj, "mouseover", function(e){alert('here');}.bind(this))
});

Now if the checkboxes are on the page at page load, the mousover trick works great.

Unfortunately, if I try and call the "$$" method in any way AFTER the checkboxes have been added to the DOM via AJAX, none of them manage to pick up their event listener.

SO ... does anyone know how to force prototype to re-read the current state of the DOM? (or any other workaround y开发者_如何学Goou can possibly think of)

I've tried putting the $$ in a function and calling it as part of the onSuccess callback, as a separate function after the ajax call has been made and outputting the whole $$ function as part of the actual AJAX values. All to no avail.

Help is greatly appreciated.


was actually ridiculously easy.

function ajax_load_keyset(obj) {
    url             = '/myurl.html';
    params          = 'id='+obj.value;
    new Ajax.Updater(   'checks_go_here',
                    url, {
                    method:'post',
                    parameters:params,
                    evalScripts: true,   // this line must be present   
                    onSuccess:  function(result){}
                });
}

turns out I only needed to add evalScripts: true to the ajax call, then put the $$ function on the /myurl.html page at the end of everything.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜