开发者

How to select a link that contains an instance of a class name?

开发者 https://www.devze.com 2023-03-17 17:08 出处:网络
right now the source code of my page has the following structure: <span id=\'648746\' class=\'topic\'>linkedin

right now the source code of my page has the following structure:

<span id='648746' class='topic'>linkedin
<a href='' class='hidden unblacklist' onclick='return false'>Restore</a>
<a href='' class='blacklist' onclick='return false'>[X]</a>
</span><br /> 

On pageload, the link with text "Restore" is hidden. When the user clicks the link, I want to add the hidden class to the开发者_如何学JAVA link that was just clicked, and then I want to remove the hidden class from the other link in the <span></span>. I can get the first part to work, but I am having difficulty with the second part. Here is my attempt:

$(this).addClass("hidden");
console.log($(this).closest("span"));
$(this).closest("span").hasClass("unblacklist")[0].removeClass("hidden");

One of the biggest difficulties of this is that the other link has two classes: "hidden" and "unblacklist". I think I would know how to do it for one class, but the game changes for two classes.

Thanks in advance!

Edit: So many answers. All of them work, too! Thanks a lot guys.


My solution would use toggleClass():

$(this).parent().children().toggleClass('hidden');


use .siblings():

$(this).addClass("hidden").siblings().removeClass("hidden");


You can use .siblings(), which either returns all siblings in the DOM or accepts a jQuery filter.

$(this).addClass("hidden");
$(this).siblings('a.unblacklist').removeClass("hidden");

Just add this code to the click() handler of your link.


You're third line is wrong. Try:

$(this).closest("span").find(".unblacklist").removeClass("hidden");


  $('a.blacklist').click(function(){
    $(this).addClass('hidden').siblings('a.unblacklist').removeClass('hidden');
    });


You could use the prev method if the "Restore" link will always come before the "[X]" link.

$(this).addClass("hidden");
$(this).prev().removeClass("hidden");


hasClass() only tells if an element exposes a class. It returns a boolean value, not a jQuery object, so you cannot chain it.

You're looking for the class selector:

$(this).closest("span").find(".unblacklist").removeClass("hidden");

That said, a pattern often used in your situation is to remove the hidden class first, by matching the elements that expose it, then add it to the element of your choice:

$(this).closest("span").find(".hidden").removeClass("hidden");
$(this).addClass("hidden");

(The above assumes that your markup can be more complicated than the example in your question, so it refrains from using siblings() to match the other anchor element.)

0

精彩评论

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