开发者

Update DOM after insert in jQuery

Let's say I use jQuery to load new content into a specific DIV element. If I now want to catch events from inside that DIV element, I assume the DOM has to be updated somehow? What is the best way to deal with this?

Edit: Here is an example of what I mean:

<html>
  <head>
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
    <script>
      $(document).ready(function(){
        $(".edit").click(开发者_Python百科function(){
          $(this).parent().load("edit");
        });
        $(".view").click(function(){
          $(this).parent().load("view");
        });
      });
    </script>
  </head>
  <body>
    <div class='someid'>
      <input type='submit' class='edit' value='Edit'>
    </div>
  </body>
</html>

where a file edit at the same level contains

<input type='submit' class='view' value='View'>

and a file 'view' contains

<input type='submit' class='edit' value='Edit'>

If you try this out you will see that when you first press Edit, the button changes to View, but then it doesn't change anymore. Why is this?


Since jQuery 1.7.x the .live() method is deprecated. Use .on() to attach event handlers. If you are using an older version you should use .delegate() in preference to .live().

As mentioned in the help, the format does not change a lot like shown in this example:

$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+

So since 1.7.x, both, delegate and live have been superseeded by on.


Use live like this:

 $(".view").live("click",function(){
      $(this).parent().load("view");
    });


jQuery uses "live" events to deal with things happening in dynamically added DOM elements without having to manually add handlers after a content-update.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜