jQuery:有没有一种方法可以自动将属性添加到动态生成的HTML中,就像live()与事件一样? [英] jQuery: Is there a way to automatically add attributes to dynamically generated HTML, in the same way that live() works with events?

查看:83
本文介绍了jQuery:有没有一种方法可以自动将属性添加到动态生成的HTML中,就像live()与事件一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下列表:

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>

我将目标属性添加到每个链接使用jQuery,因为我不想改变服务器端的HTML输出;它被用在许多其他地方,并且这是链接应该具有该属性的唯一实例。

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');

问题在于新链接会动态地附加到此列表客户端,也使用jQuery;当他们是,他们显然缺乏目标属性,所以我最终得到这样的事情:

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></li>
    <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>

我无法修改附加链接的jQuery脚本以包含属性,所以我的问题是这样的:我知道我可以使用 live()为动态生成的元素自动设置事件处理程序,但有没有办法自动添加属性添加到任何新元素?

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?

推荐答案

我不认为有什么办法可以做到你问。但您可以使用live来完成同样的事情:

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');
});

这篇关于jQuery:有没有一种方法可以自动将属性添加到动态生成的HTML中,就像live()与事件一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆