开发者

ajax on javascript created elements

开发者 https://www.devze.com 2022-12-18 05:23 出处:网络
is it possible that javascript doesnt apply to elements created trough an aj开发者_Go百科ax request?

is it possible that javascript doesnt apply to elements created trough an aj开发者_Go百科ax request? practically i have a tree of elements like parents and children with a dept of more levels.

i have the root elements on the index page and on click i can retrive the children trough this request:

var get_children = function() {
 pid = $(this).attr("id");
 //var parentid = pid
    // store value in data variable
    var data = { par: pid };
    $.getJSON("/holz/children/",data,
        function(data){
      //remove the box if it already exists
      $("#parid-" + pid ).remove();
            // Add the messages div to the container
            $("#container").append("<div class='box' id='parid-" + pid + "'></div>");
            //create the id set for the box
            boxid = "#parid-"+pid
            //insert the elements one after each other with the id set to the elements pk  
            $.each(data, function(i,item){
                $(boxid).append('<p><a '+'id="'+item.pk+'"'+' class="element" href="#">'+item.fields.title +' ( id = '+ item.pk+' )'+'</a>'+'</p>');
            });
        }
    );
  return false;
};

the problem is that i cant go deeper because the request doenst apply on the elements i got from the first request. the ajax request calls a django view which should (and it does in the on the first element) and returns a json reponse which i use to create a box with the children.

what am i doing wrong?

thx


I'm not sure I fully understand but it sounds like you want an onclick eventhandler to apply to all domelements with a certain css class .element. Am I right?

If so then just use jQuery's live() event binder syntax. This will allow you to bind an event to all dom elements that match a given selector now, and in the future.

To use some of your own code as an example:

$('div.box').live('click', function() {
    alert('you clicked me!');
});

$("#container").append("<div class='box' id='parid-" + 1 + "'></div>");

In the example above the div that we added dynamically will have our click event bound to it since we used the jquery api to insert it.


Nope, JavaScript always applies to every valid element in the DOM, no matter where it came from.

I can't really make much sense out of your code yet, but maybe your AJAX call is injecting elements with IDs that already exist in the document? That would cause trouble when trying to address those elements.

0

精彩评论

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