简体   繁体   English

在具有相同href的多个锚之间获取锚文本值

[英]Get an anchor text value among multiple anchor's with same href

My html is我的 html 是

<a id='_requestOne' href='#applynow'> apply one </a>

<a id='_requestTwo' href='#applynow'> apply two </a>

<a href='#applynow'> apply three </a>

I want to change the anchor text for the second one alone.我想单独更改第二个的锚文本。 so I implemented in script as所以我在脚本中实现为

$("a[href='#applynow']").text("request call");

Its changing all the three tags, so I tried as它改变了所有三个标签,所以我尝试了

$("#_requestTwo a[href='#applynow']").text("request call");

But its not working.但它不起作用。 Can anyone give me a solution that how could I declare both id & href in same call.谁能给我一个解决方案,我怎么能在同一个调用中同时声明 id 和 href 。

Thanks in advance.提前致谢。

What you can do is target the second Item of the jQuery Object:您可以做的是定位 jQuery 对象的第二个项目:

$( $("a[href='#applynow']")[1] ).text('request call') //starts counting at 0

I do not advise on this, it makes the code less maintenable if the html markup changes.我不建议这样做,如果 html 标记更改,它会使代码的可维护性降低。 You have an ID, so use that instead.你有一个 ID,所以用它代替。

$("#_requestTwo").text('request call')

PS: PS:

The reason why your second try doesn't work is because you had an error in the selector:您的第二次尝试不起作用的原因是因为您在选择器中出错:

$("#_requestTwo a[href='#applynow']") 
//should be 
$("a[href='#applynow']#_requestTwo") 

First select anchors with href then specify with ID or select directly by ID because ID should be unique:首先使用 href 选择锚点,然后使用 ID 指定或直接通过 ID 选择,因为 ID 应该是唯一的:

 $("a[href='#applynow']#_requestTwo").text("request call");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id='_requestOne' href='#applynow'> apply one </a> <a id='_requestTwo' href='#applynow'> apply two </a> <a href='#applynow'> apply three </a>


Always select elements from low to high specificity like:始终选择从低到高特异性的元素,例如:

$("tagname.class");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM