开发者

adding functions to injected elements

Okay how can i add function to injected elements(which that element dosent exist on first browser load). Please read through my example carefully , i hope you can understand.

For example: i go to www.website.com , when it loads it loads up "functions.js" and "other.js" , inside "functions.js" there's a code that injects a new div with ID wh开发者_运维问答en user click on a button.

The injection code as shown below:(functions.js --jquery)

$('a#button').click(function(){
    $('a#button').after('<div id="new">New div<br><a href="#" id="newdivlink">Another link</a></div>');
});

However there's another on click functions loaded in another js file which is "other.js" (loaded same time as function.js load).

Inside "other.js" has the code for the onclick function when the new div's link (#newdivlink) is clicked.

other.js :

$('a#newdivlink').click(function(){
  alert('you clicked on new div's link yay?');
});

But the problem is , the onclick function for the new div's link(#newdivlink) cant be executed as the script can't find the div (as it is being injected after i loads). Or is there some problems ?

P/S if you are asking why not combine both scripts , i don't want, as i want to try this technique out.


Try using 'live' instead of click:

$('a#newdivlink').live('click', function(){


use live() for jQuery version < 1.7 or on() for version >= 1.7


What you probably need is jQuery.live.

$('a#newdivlink').live("click", function(){
    alert('you clicked on new div's link yay?');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜