Jquery:将rel属性添加到某个类的所有<li>标签中的<a>标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5767025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:47:37  来源:igfitidea点击:

Jquery: Add rel attribute to <a> tags within all <li> tags of a certain class

jqueryattributeslightboxaddrel

提问by Saahir Foux

I'm trying to add a rel="lightframe"attribute to all my 'edit' links within my admin_links_node_editclass.

我正在尝试为班级中的rel="lightframe"所有“编辑”链接添加一个 属性admin_links_node_edit

<li class="admin_links_node_edit">
<a href="[link]" title="Edit">Edit</a>
</li>

My code so far looks like this:

到目前为止,我的代码如下所示:

$('.admin_links_node_edit a').each(function() {
        $(this).attr('rel','lightframe'); 
});

回答by Vijay Dev

You don't need to use each(). jQuery's selectors will do it for you :)

您不需要使用 each()。jQuery 的选择器会为你做这件事 :)

$('.admin_links_node_edit a').attr('rel', 'lightframe')

The above code will do the trick.

上面的代码可以解决问题。

回答by Kyte

If admin_links_node_editis reused among other elements, you'll want to specify the element you're working on (liin this case). In addition, as Vijay Dev said, each() isn't needed, as attr() works on every element in the selector. Therefore:

如果admin_links_node_edit在其他元素中重复使用,您需要指定您正在处理的元素(li在本例中)。此外,正如 Vijay Dev 所说,each() 不是必需的,因为 attr() 对选择器中的每个元素都起作用。所以:

$("li.admin_links_node_edit a").attr('rel','lightframe');