[英]Jquery Attribute selector click
I'am trying to select a div
with a specific attribute. 我正在尝试选择具有特定属性的
div
。 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. 我想
div
被点击只有在有特定的attribute
与true
价值。问题是,如果我点击div
再次提醒仍显示,而它的attribute
与false
值。
HTML 的HTML
<a href="#" data-spinner="true">Click Here</a>
Jquery jQuery的
$("a[data-spinner='true']").click(function() {
$("a[data-spinner='true']").attr("data-spinner",false);
alert("clicked");
});
The 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. 请注意,此方法允许您使用
data()
方法,这是更好的做法。
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. 您也可以在第一次单击时使用
off()
删除事件处理程序,或仅使用one()
附加事件-取决于页面中设置data
属性值的其他逻辑。
jQuery doesn't redeclare the event when you change the value of data-spnner
. 当您更改
data-spnner
的值时,jQuery不会重新声明该事件。 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);
});
我要在Rory McCrossan的回答中添加一点,相应于此 ,您还应该使用removeAttr取消设置属性:
$("a[data-spinner='true']").removeAttr("data-spinner");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.