开发者

Get the href of the previous sibling and update the href of the current item

开发者 https://www.devze.com 2023-01-21 13:59 出处:网络
I\'ve ended up and done this by hand, but I was thinking this could be done much quicker with some jquery.

I've ended up and done this by hand, but I was thinking this could be done much quicker with some jquery.

I have a table with dozens of the example rows below. What I'd like to do is find the previous siblings of the <a href="#">, grab their URL, change the filetype to .doc and apply.

<tr id="node-20" class="child-of-node-19">
        <td>Tips</td>
        <td>
        <a href="docs/Interview-Info.pdf">
          <img width="20" height="20" src="/images/icons/icon-pdf.gif" alt="PDF" />
        </a> 
        <a href="#">
          <img width="20" height="20" src="/images/icons/icon-word.gif" alt="Microsoft Word" />
      开发者_JAVA技巧  </a>
        </td>
    </tr>

So once the javascript is complete, the generated source would look like this.

<tr id="node-20" class="child-of-node-19">
        <td>Tips</td>
        <td>
        <a href="docs/Interview-Info.pdf">
          <img width="20" height="20" src="/images/icons/icon-pdf.gif" alt="PDF" />
        </a> 
        <a href="docs/Interview-Info.doc">
          <img width="20" height="20" src="/images/icons/icon-word.gif" alt="Microsoft Word" />
        </a>
        </td>
</tr>

My last variation was:

$('a+a[href="#"]').attr('href',$('a+a[href="#"]').prev().attr('href'));

That ends up getting the first url, and applying it to all the <a href="#">. So Interview-Info.pdf is applied to all those links.

This is as far as I got due to time contraints. Is there a simple was to do this?


.attr() only works with the first element in the set, so you probably want to iterate over your list and apply it to each:

$('a+a[href="#"]').each(function() { 
  $(this).attr('href', $(this).prev().attr('href').replace(/\.[a-z0-9]+$/i, '.doc')); 
});


you're almost there, try this:

$('a+a[href="#"]').attr('href',$('a+a[href="#"]').prev().attr('href').replace(/.pdf/gi, ".doc"));
0

精彩评论

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

关注公众号