开发者

Using .live() to make jQuery plugin affect new element added via Ajax

开发者 https://www.devze.com 2023-04-08 09:50 出处:网络
I am building a stream (similar to Facebook wall) that inserts new posts via Ajax. I also use the jQuery plugin Linkify to transform any link strings into a clickable element.

I am building a stream (similar to Facebook wall) that inserts new posts via Ajax.

I also use the jQuery plugin Linkify to transform any link strings into a clickable element.

When a user enters a link, the post is immediately shown on the page (via Ajax) but Linkify does not affect is since it wasn't in the DOM to begin with. When I reload the page, the link is then clickable.

Is there a way of using .live() to make a plugin affect future DOM elements added by ajax?

Some code:

//-------------Linkify

$('.main_container').linkify();

//-------------stream page structure

<div class="main_container">
    <div class="posts_insert">
         // target to be replaced via ajax
    </div>
    <div class="posts">
         // text of post #1
    </div>
 开发者_运维百科   <div class="posts">
         // text of post #2
    </div>
    <div class="posts">
         // text of post #3
    </div>
</div>

//----------post structure, will replace .posts_insert above

<div class="posts_insert">
     // text of post #1
</div>
<div class="posts">
     // html
</div>


insert the line $('.main_container').linkify(); into the success function of your ajax call...

eg:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(result){
    //Your functions here
    $('.main_container').linkify();
  }
});

This makes sure the linkify function is called AFTER new content is added to the page, affecting new posts :)

** EDIT: just clarifying, linkify should be called twice, once on page load and then once on ajax success :)


no, .live() is for attaching event handlers. you will need to process new data in your ajax success handler.


You can upgrade linkify source code itself and use .live() instead of .click() and other event binding used in linkify. There is few code change needed. Just like this one:

Line 239: $(this).click(function()... ==> $(this).live('click', function()...

0

精彩评论

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

关注公众号