开发者

Making all links inside of a div call the same function?

开发者 https://www.devze.com 2022-12-27 23:44 出处:网络
I\'m trying to make a notification area that will show alerts. return this.each(function() { jQuery(\'<div class=\"\' + o[\'className\'] + \'\">\' + o.msg + \' +

I'm trying to make a notification area that will show alerts.

return this.each(function() {
  jQuery('<div class="' + o['className'] + '">' + o.msg + ' +
         '<a href="#" onclick="$(this).parent().remove(); dismiss(' + o["id"] + ');">X</a>' + '</div>')
    .appendTo(this);
});

This just takes a message pulled from the database, and shows it to the user. If the user clicks the X then it will call dismiss() which will mark it as being read in the database.

The thing is, if the message itself contains a link to another page or external site, I also want to call dismiss() before the user leaves the page. Is there anyway to alter this javascript to take all a elements (the X and any links that would appea开发者_StackOverflow中文版r in the message) and change the onclick to call the function?


You can rearrange your code a bit and use .delegate(), like this:

return this.each(function() {
  var id = o["id"];
  jQuery('<div />', { 'class': o['className'], html: o.msg })
   .append('<a href="#">X</a>')
   .delegate('a','click', function() { $(this).parent().remove(); dismiss(id); })
   .appendTo(this);
});

This uses the new jQuery(html,props) added in jQuery 1.4 to make the creation a bit cleaner (and faster! document fragment caching!). What it's doing is instead of attaching an onclick to the X, it's listening for a click from any <a> in the div and when it bubbles, it executes the same code as it used to only on the <a href="#">X</a> anchor.


The code example is a bit vague, where does this o come from? Is it global or something div-specific?

At any way, you may find jQuery.live() useful for this. Once initialized, it will be applied on all future new elements matching the selector. You only need to have some parent element which is going to contain all of those divs with the messages and the links.

$('#someDivId a').live('click', function() {
    // Do your thing here as you did in `onclick` attribute.
};

Just execute it once during onload.

0

精彩评论

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