如何隐藏元素第二次被点击 [英] How to hide element the second time it's clicked

查看:172
本文介绍了如何隐藏元素第二次被点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在元素被第一次点击(使用jQuery)之后隐藏元素,以便用户在此之后无法看到并点击元素。



如何

解决方案

非常简单:

/ p>

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

jQuery选择器(例如点击隐藏使所有具有类的点击隐藏的元素具有这种行为)。隐藏元素是使用jQuery 隐藏 完成的方法(如果您想让元素稍后可见,则还有 show )。



打算在元素首次隐藏后对其进行任何操作,您可能还需要考虑 remove 而不是隐藏



Update:要在第二次点击时执行某些操作,您需要记住在某个元素上是否已进行了点击。如果它不会变得更复杂,你可以使用一个类为这个目的:

  $(selector) .click(function(){
var $ this = $(this);
if($ this.hasClass(clicked-once)){
//已被点击一次,隐藏它
$ this.hide();
}
else {
//第一次被点击,标记为
$ this.addClass(clicked- once);
}
});

如果要计算点击次数,可以使用 data 函数来存储元素已收到的点击量:

  $(selector)。click(function(){
var $ this = $(this);
b $ b //当前点击计数是前一次点击计数+1
var clickCount =($ this.data(click-count)|| 0)+ 1;

保存当前点击计数
$ this.data(click-count,clickCount);

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


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.

解决方案

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();
    }
});

这篇关于如何隐藏元素第二次被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆