x 次后禁用点击
假设用户可以单击按钮 (div) 7 次。单击 7 次后,该按钮必须消失或变得不可单击。我该怎么做?
Let's say the user is able to click a button (div) 7 times. After clicking it 7 times, the button must disappear or become non clickable. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
尽管您需要自己充实一些细节,但这应该可行。按钮:
JS:
我只是停止处理点击,但是您当然可以隐藏该按钮,而不需要太多的努力。
This should work although you'll need to flesh out some details yourself. The button:
The JS:
I've simply stopped processing the click, but you can hide the button of course without too much effort.
像这样的东西应该有效:
这样,您可以避免全局变量并使计数与其所属的特定元素相关联。 (想象一下,如果您有数百个这样的按钮!)
Something like this should work:
This way, you avoid global variables and keep your count associated to the particular elements it pertains to. (Just imagine if you have hundreds of these buttons!)
至少有两种方法可以做到这一点...
使用闭包
只需在事件处理程序外部定义变量并在每次单击时增加它。然后检查它有什么价值。它可能如下所示:
使用 jQuery.data() 将点击计数器关联到元素
您还可以使用 jQuery 的功能之一将数据附加到元素。它可能看起来像这样:
实例
您可以看到两个代码都正常工作 - 只需点击此链接即可观看演示: http:// jsfiddle.net/3wt8h/
jQuery 免责声明 < 1.7
如果您的 jQuery 版本早于 1.7,您将无法使用
.on()
函数。只需使用.bind()
即可,它的工作原理应该完全相同。There are at least two methods of doing this...
Using closure
Just define variable outside the event handler and increase it with every click. Then just check what value it has. It could look like this:
Associating click counter to the element using
jQuery.data()
You can also use one of the jQuery's features for attaching data to the elements. It could look like this:
Live examples
You can see both codes work correctly - just follow this link to the demo: http://jsfiddle.net/3wt8h/
Disclaimer for jQuery < 1.7
If your version of jQuery is older than 1.7, you will not have
.on()
function available. Just use.bind()
instead, it should work exactly the same.click
处理程序visible
css 类设置为隐藏。click
handler to the divvisible
css class to hidden.简短的答案是增加一个变量作为点击操作的一部分以跟踪按钮被点击的次数。
您应该避免将此变量设置为全局变量。您可以通过在函数范围内声明该变量来实现此目的,并让该函数设置点击行为。
使用 jQuery:
The short answer is to increment a variable as part of the click action to keep track of the number of times the button has been clicked.
You should avoid having this variable be global. You can do this by declaring the variable within the scope of a function, and have that function set up the click behavior.
With jQuery:
当然,在你的 html 中添加带有相关类的按钮,
IE:
and off course in your html add the button with the relevant class,
i.e.:
这就是我要做的
http://jsfiddle.net/einar/E9Wkr/
This is what I would do
http://jsfiddle.net/einar/E9Wkr/