开发者

How to hide element the second time it's clicked

I want to hide an element after it is first clicked (using jQuery), so that user can't see and click the element after that.

How can I do that?

Thanks.开发者_Python百科


Very simply:

$("selector").click(function() { $(this).hide(); });

"selector" above would be any valid jQuery selector (e.g. ".click-to-hide" to make all elements with class click-to-hide have this behavior). Hiding the element is done using the jQuery hide method (there is also show if you want to make the elements visible again later).

If you do not intend to do anything at all with the elements after they are hidden for the first time, you might also want to consider remove instead of hide.

Update: To do something on the second click, you need to remember when a click has already been made on an element. If it's not going to get more complicated than that, you could use a class for this purpose:

$("selector").click(function() {
    var $this = $(this);
    if ($this.hasClass("clicked-once")) {
        // already been clicked once, hide it
        $this.hide();
    }
    else {
        // first time this is clicked, mark it
        $this.addClass("clicked-once");
    }
});

If you want to count the clicks, you can use the data function to store the amount of clicks the element has received:

$("selector").click(function() {
    var $this = $(this);

    // Current click count is previous click count +1
    var clickCount = ($this.data("click-count") || 0) + 1;

    // Save current click count
    $this.data("click-count", clickCount);

    if (clickCount == 1) {
        $this.hide();
    }
});


I can't comment, but I think the code I use works better than the original answer.

$("#slider").click(function() {
    if ($('#slider').hasClass("clicked-once")) {
			$('#menu').slideUp(1000);
			$('#slider').removeClass("clicked-once");
    }
    else {
			$('#slider').addClass("clicked-once");
			$('#menu').slideDown(1000);
    }
});

It's just much more simple and compressed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜