开发者

jQuery: Is there a way to automatically add attributes to dynamically generated HTML, in the same way that live() works with events?

开发者 https://www.devze.com 2023-03-19 16:00 出处:网络
I have a list like the following: <ul id=\"links\"> <li><a href=\"/example-url-1\">Link 1</a></li>

I have a list like the following:

<ul id="links">
    <li><a href="/example-url-1">Link 1</a></li>
    <li><a href="/example-url-2">Link 2</a></li>
    <li><a href="/example-url-3">Link 3</a></li>
</ul>

I'm adding a target attribute to each link using jQuery, because I don't want to alter the server-side HTML output; it's used in many other places and this is the only instance where the links should have this attribute.

$('#links a').attr('target', '_top');

The problem is that new links are dynamically appended to this list client-side, also using jQuery; when they are, they obviously lack the target attribute, so I end up with this sort of thing:

<ul id="links">
    <li><a href="/example-url-1" target="_top">Link 1</a></l开发者_高级运维i>
    <li><a href="/example-url-2" target="_top">Link 2</a></li>
    <li><a href="/example-url-3" target="_top">Link 3</a></li>
    <li><a href="/example-url-4">Link 4</a></li>
</ul>

I cannot alter the jQuery script which is appending the links in order to include the attribute, so my question is this: I know I can use live() to automatically set up event handlers for dynamically generated elements, but is there a way of automatically adding attributes to any new elements added?


I don't think there's any way to do what you're asking. But you can use live to accomplish the same thing:

$('#links a').live("click", function(e) {
   $(this).attr('target', '_top');
});


If you're not averse to plugins, you might take a look at livequery, which will accomplish what you want.

Here's an example:

$("#links a").livequery(function () {
    $(this).prop("target", "_top");
}); 

http://jsfiddle.net/vRF3G/


You might want to look into jQuery's special event system. It allows you to create custom special events that get triggered when certain conditions are met.

Here's another SO thread with a "onContentChange" event: Create a jQuery special event for content changed

And here's another article on jQuery Custom Special Events: http://benalman.com/news/2010/03/jquery-special-events/


This is a terrible solution:

$("#links a").live("mouseover", function() { $(this).attr("target","_top"); });

Can't click on it without mousing over it, the target attribute is set before it is needed.

0

精彩评论

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

关注公众号