开发者

jquery replace query

I would like to alter the href attribute for all anchor tags within a particular div.

<div id="xyx">
    <ul> 
        <li><a href="xyz/-1"/></li>
        <li><开发者_如何转开发a href="abc/-1"/></li>
        <li><a href="cab/-1"/></li>
    </ul>
</div>

I would like to replace this with:

<div id="xyx">
    <ul> 
        <li><a href="xyz/-2"/></li>
        <li><a href="abc/-2"/></li>
        <li><a href="cab/-2"/></li>
    </ul>
</div>

i.e. I want to replace -1's to -2's.

How can this be done in jQuery?


$('#xyx ul li a').attr('href',function(i,href){ 
    return href.replace('-1','-2'); 
});
  • $('#xyx ul li a') target the proper <a> elements.

  • Call the attr()(docs) method to reference the href attribute.

  • Pass a function that will be invoked once for each <a> element.

  • Have the function perform a .replace()(docs) on the href and return the result to .attr().


Use the attr method, and pass a function to it. This executes the function on each element within the jQuery set, changing the provided attribute to the value returned by the function.

jQuery passes the current value of the attribute as the second parameter of the function (which will be current "href" value in this case), so we simply replace the -1 occurances with -2.

$('#xyx a').attr('href', function(i, href) { 
    return href.replace('-1','-2'); 
});


Try this

$("#xyx ul").find("li:nth-child(1) a").attr("href", "url");

You can change the number "1" to whichever number link you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜