【问题标题】:JQuery: Set attribute for nth element by name selectorJQuery:按名称选择器设置第 n 个元素的属性
【发布时间】:2016-09-03 02:54:56
【问题描述】:

拥有一组同名的“a”标签:

<a name="link" href="http://link1">
<a name="link" href="http://link2">
<a name="link" href="http://link3">

我需要使用$("['name=link']") 选择器更改第三个元素的 href 属性,但不能使用 prop/attr 方法。

【问题讨论】:

  • 尽可能为它创建 jsfiddle...
  • 试试这个.. $("[name='link']")
  • 锚点上的名称属性已过时。
  • 试试这个 $("[name='link']:eq(2)")
  • 你的意思是$('a[name="link"]:nth-child(3)')?

标签: jquery html jquery-selectors


【解决方案1】:

我正在尝试理解您的问题。

根据您的解释,我建议您尝试使用 ":eq" jQuery Selector。代码会是这样的:

// eq takes element by index (from 0 to *) in the same 'root' of nodes in DOM structure
$("a[name='link']:eq(2)").attr('href', '__new value__');

这里是这个特性的官方 jQuery 文档:https://api.jquery.com/eq-selector/

工作示例:

$(document).ready(function() {
  $("a[name='link']:eq(2)").attr('href', '__new value__');

  // checking the href value in the console
  console.log($("a[name='link']:eq(2)").attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a name="link" href="http://link1">1st link</a>
<a name="link" href="http://link2">2nd link</a>
<a name="link" href="http://link3">3rd link</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 2011-03-18
    • 1970-01-01
    • 2016-04-06
    • 2014-01-20
    • 1970-01-01
    • 2021-10-03
    相关资源
    最近更新 更多