use*_*989 3 jquery click onclick
我想在首次单击元素(使用jQuery)后隐藏它,这样用户就无法看到并单击该元素.
我怎样才能做到这一点?
谢谢.
非常简单:
$("selector").click(function() { $(this).hide(); });
Run Code Online (Sandbox Code Playgroud)
"selector"上面将是任何有效的jQuery选择器(例如".click-to-hide",使所有带有类的元素click-to-hide都有这种行为).使用jQuery hide方法隐藏元素(show如果您希望稍后再次显示元素,也可以使用它).
如果您在第一次隐藏元素后不打算对元素执行任何操作,您可能还需要考虑remove而不是hide.
更新:要在第二次单击时执行某些操作,您需要记住何时对元素进行了单击.如果它不会变得更复杂,你可以使用一个类来实现这个目的:
$("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");
}
});
Run Code Online (Sandbox Code Playgroud)
如果要计算点击次数,可以使用该data函数存储元素收到的点击次数:
$("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();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13097 次 |
| 最近记录: |