如何通过属性的最后部分选择元素

时间:2016-04-29 08:21:15

标签: jquery attributes anchor href

我想仅为target="_blank"元素添加<a>,其中href的最后一部分为page2.aspx。我怎么能用jQuery做到这一点?我试过这个:

$j("a[href='page2.aspx']").attr('target', '_blank'); // not sure if it works?
<a href="/en-gb/mypage/Pages/page1.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page2.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page3.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page4.aspx">My Site</a>

由于每次页面呈现时的变化(语言)更改,我无法像下面一样访问<a>

$j("a[href='/en-gb/mypage/Pages/page2.aspx']").attr('target', '_blank');

我该如何解决?

1 个答案:

答案 0 :(得分:2)

您可以使用Attribute ends with选择器:

$j("a[href$='page2.aspx']").prop('target', '_blank');

$("a[href$='page2.aspx']").prop('target', '_blank');

// here's something that makes a visible difference so you 
// can see the element is targeted properly
$("a[href$='page2.aspx']").css('color', '#C00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/en-gb/mypage/Pages/page1.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page2.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page3.aspx">My Site</a>
<a href="/en-gb/mypage/Pages/page4.aspx">My Site</a>