我试图让jQuery仅在特定时间监听点击。但是,当我添加事件监听器(例如$("#box").click(function(){
)时,它们似乎在它们上面的代码运行之前就已执行。
我创建了一个文本示例,其中有2个不同的框用于监听点击,我只希望第二个框在单击第一个框之后监听。之后,我希望他们停止收听。因此,例如box1
应该能够先更改为红色,然后再更改为box2
。
我尝试搜索此问题,但找不到任何好的答案。我也尝试添加if
语句,但是第二个框从不执行。任何帮助将不胜感激。
pass = 0;
function change() {
console.log("enter change");
$("#box").click(function() {
$(this).css("background-color", "red");
pass = 1;
})
if (pass > 0) {
$("#box2").click(function() {
$(this).css("background-color", "red");
})
}
}
div {
height: 100px;
width: 100px;
background-color: black;
display: inline-block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div id="box"></div>
<div id="box2"></div>
<button onclick="change()"> change</button>
答案 0 :(得分:1)
To make this work I'd suggest using a different pattern. Having click handlers attached at dynamic times can get confusing and make the code more complex than it needs to be.
A simpler and more effective solution would be to bind all the event handlers when the page loads, and conditionally check within each if the page is in a state in which this event handler is allowed to execute its own logic.
In other words, you could add a class on click of #box
and then only allow the class to be added on #box2
once it has been applied to #box
. Try this:
$('#box').one('click', function() {
$(this).addClass('foo');
});
$('#box2').click(function() {
if ($('#box').hasClass('foo')) {
$(this).addClass('foo').off('click');
}
});
div {
height: 100px;
width: 100px;
background-color: black;
display: inline-block;
margin: 10px;
}
div.foo {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"></div>
<div id="box2"></div>
There's a few things to note here. Firstly, jQuery 1.4.2 is very outdated; almost 9 years in fact. You need to updated it to at least 1.12.4 if you require legacy browser support, or the latest on the 3.x branch if not.
Secondly, don't use inline event handlers, such as onclick
. Use unobtrusive event handlers. As you're already using jQuery it's easy to just use the click()
method.
This also uses one()
, to add an event handler which can only fire once, and off()
to remove the click handler once it's been executed successfully for the first time.
It also uses addClass()
over css()
, as the latter requires you to put CSS logic within your JS, which should be avoided where at all possible.