开发者

jQuery. Switching between elements

开发者 https://www.devze.com 2023-03-14 19:38 出处:网络
I have this html code <a href=\"#\">Link</a> <div>Content</div> <a href=\"#\">Link</a>

I have this html code

<a href="#">Link</a>
<div>Content</div>
<a href="#">Link</a>
<div>Content</div>

and this jQuery

$('a').click(
function(){
    $("div:visible").slideUp(100),
    $(this).next("div:hidden").slideDown(100),
    $('a').css({"font-weight" : "normal"}),
    $(this).css({"font-weight" : "bold"});
});

The idea is that after I click the link next div becomes visible. Link itself becomes bold. Click on the another link hides any visible div, removes bold from any link and opens new div and makes another link bold.

Quite simple and works ok with only one exception: after I click the same link second time I don't need it to be bold. I understand that this hap开发者_如何学编程pens because of the last line of the jQuery code but can't find another solution.

Thank you!


You could check if the current link is already bold. If not, then make it so.

if ($(this).css("font-weight") != "bold") {
  $(this).css({"font-weight" : "bold"});
}


You can use the jQuery.data function to store metadata about DOM elements.

So in your case, change last line:

$(this).css({"font-weight" : "bold"});

to:

if ($(this).data('clicked') == undefined) $(this).css({"font-weight" : "bold"});
$(this).data('clicked', true);

Enjoy!


use toggleClass() in this case

in your css write this-

.normal{"font-weight" : "normal"}
.bold{"font-weight" : "bold"}

in jquery -

$('a').click(  function(){ 

$('a.bold').removeClass('bold'); // will remove bold class from all link   

$("div:visible").slideUp(100),     
 $(this).next("div:hidden").slideDown(100)      

$(this).toggleClass('normal bold') ;

}); 
0

精彩评论

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

关注公众号