admin管理员组文章数量:1320661
I'am trying to select a div
with a specific attribute. I want the div
to be clicked only if there is a specific attribute
with a true
value.The problem is that if i click the div
again the alert still shows up whereas it has the attribute
with false
value.
HTML
<a href="#" data-spinner="true">Click Here</a>
Jquery
$("a[data-spinner='true']").click(function() {
$("a[data-spinner='true']").attr("data-spinner",false);
alert("clicked");
});
I'am trying to select a div
with a specific attribute. I want the div
to be clicked only if there is a specific attribute
with a true
value.The problem is that if i click the div
again the alert still shows up whereas it has the attribute
with false
value.
HTML
<a href="#" data-spinner="true">Click Here</a>
Jquery
$("a[data-spinner='true']").click(function() {
$("a[data-spinner='true']").attr("data-spinner",false);
alert("clicked");
});
Share
Improve this question
asked Aug 18, 2016 at 14:14
zaarr78zaarr78
47710 silver badges23 bronze badges
1
- 1 Either remove the event handler after the first click, or use event delegation. – C3roe Commented Aug 18, 2016 at 14:17
3 Answers
Reset to default 7The issue with your current code is that you attach the event when the element has the attribute. The fact you change the attribute afterwards does not remove that event handler, so it is always called.
There are several ways to fix this.
The first is to use a delegated event handler, which will always account for the current attribute value:
$(document).on('click', 'a[data-spinner="true"]', function() {
$(this).attr("data-spinner", false);
alert("clicked");
});
Another method is to check the state of the attribute within the click handler itself:
$("a[data-spinner]").click(function() {
if ($(this).data('spinner')) {
$(this).data('spinner', false)
alert("clicked");
});
});
Note that this method allows you to use the data()
method which is considered better practice.
You could also remove the event handler using off()
on the first click, or just use one()
to attach the event - depending on the other logic in the page which sets the data
attributes' value.
jQuery doesn't redeclare the event when you change the value of data-spnner
.
You must programatically handle that instead, like so:
$("a[data-spinner]").click(function() {
var $this = $(this);
if($this.data('spinner')){
alert("clicked");
}
$this.data('spinner',false);
});
I'd add to Rory McCrossan's answer that, accordingly to this, you also should unset the attribute using removeAttr:
$("a[data-spinner='true']").removeAttr("data-spinner");
本文标签: javascriptJquery Attribute selector clickStack Overflow
版权声明:本文标题:javascript - Jquery Attribute selector click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742065340a2418799.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论