开发者

append title to link (a href) tag based on state of link

$("a[rel='view-show-info']").click(function() {
    $(this).parent().next('.show-info').slideToggle(70);

    var img = $("img", this).attr("src");
  if( img == "<?=base_url();?>assets/images/plus.png") // or check the end of the path or similar
   $("img", this).attr("src", "/images/minus.png");
  else
   $("img", this).attr("src", "/images/plus.png");

    return false;
});

<a href="#" rel="view-show-info" class="view-more">
  <img src="/images/plus.png" alt="expand selection">
</a>

This displays a plus or minus image, based on what the user has clicked.

I want to append a title to the link, if the image is displaying the minus.png image, set the title to title="contract selection" and if it is displaying the plus.png image, set it to title="expand selection"

so the link would be like:

minus.png:

<a href开发者_运维百科="#" rel="view-show-info" class="view-more" title="contract selection">
  <img src="/images/minus.png" alt="contract selection">
</a>

plus.png

<a href="#" rel="view-show-info" class="view-more" title="expand selection">
  <img src="/images/plus.png" alt="expand selection">
</a>

I imagine I have to use the append function but that is as much as I know, any help is appreciated.


You can use .closest to traverse up the tree and locate the anchor (so you can alter it's title attribute):

var src = '/images/plus.png';
var title = 'expand selection';
if( img == "<?=base_url();?>assets/images/plus.png")
{
  src = '/images/minus.png';
  title = 'collapse selection';
}
$("img", this) // grab your image (per normal)
  .attr({'src':src,'alt':title}) // change the source
  .closest('a') // go up the three to find the anchor
  .attr('title',title) // change the anchor's title

EDIT oops, you were going for the anchor.
EDIT2 Changed aroudn the code a bit to make it a tad more streamline. Also now changes the img alt attribute as well. (Still working on IE)


if( img == "<?=base_url();?>assets/images/plus.png"){
    $("img", this).attr("src", "/images/minus.png").parent().attr('title', 'contract selection');
} else {
    $("img", this).attr("src", "/images/plus.png").parent().attr('title', 'expand selection');
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜