简体   繁体   English

如何监听“计数”变量的变化并根据其值触发动作

[英]How to listen to a "count" variable change and trigger actions depending on its value

I have a counter on a web page and I would like to change an element's style depending on the value of my count variable.我在 web 页面上有一个计数器,我想根据计数变量的值更改元素的样式。

I found the.change action but can't figure how to make it work.我找到了 .change 动作,但不知道如何让它发挥作用。 It may be not a suited solution.这可能不是一个合适的解决方案。

Could you help?你能帮忙吗?

 var count = 0; counter.innerHTML = count + "/30"; document.getElementById("button").onclick = function() { count++; counter.innerHTML = count + "/30"; } $(count).change(function(){ var x = document.getElementById("changed"); if (count >= 5) { x.style.color = "red"; }})
 <div id="counter"> Counter </div> <div id="button">Click to add 1 </div> <div id="changed">This must turn red when counter > 5 </div>

Since the counter is only updated by your code, you can directly add the check after you increment the count.由于计数器仅由您的代码更新,因此您可以在增加计数后直接添加检查。

 var count = 0; counter.innerHTML = count + "/30"; var x = document.getElementById("changed"); document.getElementById("button").onclick = function() { count++; if (count >= 5) { x.style.color = "red"; } counter.innerHTML = count + "/30"; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="counter"> Counter </div> <div id="button">Click to add 1 </div> <div id="changed">This must turn red when counter >= 5 </div>

If you are incrementing the counter in multiple places, you can use a function to encapsulate the updating and checking of the value.如果要在多个地方递增计数器,则可以使用function来封装值的更新和检查。

 var count = 0; counter.innerHTML = count + "/30"; var x = document.getElementById("changed"); document.getElementById("button").onclick = function() { updateCount(1); counter.innerHTML = count + "/30"; } function updateCount(inc){ count += inc; if (count >= 5) { x.style.color = "red"; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="counter"> Counter </div> <div id="button">Click to add 1 </div> <div id="changed">This must turn red when counter >= 5 </div>

As mentioned, you cannot "react" to variable changes (unless they're properties of an object, in which case you could define a setter that reacts in the way you need).如前所述,您不能对变量更改做出“反应”(除非它们是 object 的属性,在这种情况下,您可以定义一个以您需要的方式做出反应的设置器)。

Instead, just check the variable in those places where they are changed:相反,只需在变量发生变化的地方检查变量:

 let count = 0; const counter = document.getElementById("counter"); counter.textContent = count + "/30"; function incrementCount() { count++; } function updateCounter() { counter.textContent = count + "/30"; } function checkCounterGreaterThanFour() { if (count >= 5) { document.getElementById("changed").style.color = "red"; } } document.getElementById("button").addEventListener('click', incrementCount); document.getElementById("button").addEventListener('click', updateCounter); document.getElementById("button").addEventListener('click', checkCounterGreaterThanFour);
 <div id="counter"></div> <button type="button" id="button">Click to add 1</button> <div id="changed">This must turn red when counter > 5</div>

Things I've changed on top of those mentioned:在提到的那些之上我已经改变的事情:

  • changed var to either let or const .var更改为letconst var isn't used any more unless you need its very specifics var不再使用,除非你需要它的细节
  • changed div#button to a real button element for better semanticsdiv#button更改为真正的button元素以获得更好的语义
  • properly defined all variables using document.getElementById .使用document.getElementById正确定义所有变量。 I know all elements with a unique id are available as global variables in the browser, but code should never rely on that as any other part of the code could have modified/overwritten those我知道所有具有唯一 id 的元素都可以在浏览器中作为全局变量使用,但代码不应该依赖它,因为代码的任何其他部分都可以修改/覆盖那些
  • changed button.onclick =... to button.addEventListener('click', ... . Preferrably always use addEventListener which allows to add as many listeners as you want, whereas onclick property can always only reference one handlerbutton.onclick =...更改为button.addEventListener('click', ... 。最好始终使用addEventListener ,它允许添加任意数量的侦听器,而onclick属性始终只能引用一个处理程序
  • split the click into three functions for re-use.click拆分为三个功能以便重复使用。 Event listeners, when the event occurs, will be run in the order they have been added by the code.事件侦听器,当事件发生时,将按照代码添加它们的顺序运行。

Consider the following jQuery example.考虑以下 jQuery 示例。

 $(function() { var count = 0; $("#button").click(function() { $("#counter").html("Counter: " + ++count + "/30"); if (count > 5) { $("#changed").css("color", "red"); } }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="counter">Counter</div> <div id="button">Click to add 1</div> <div id="changed">This must turn red when counter > 5</div>

If you prefer Native JS, consider the following.如果您更喜欢 Native JS,请考虑以下事项。

 var count = 0; document.getElementById("button").addEventListener("click", function() { document.getElementById("counter").innerHTML = "Counter: " + ++count + "/30"; if (count > 5) { document.getElementById("changed").style.color = "red"; } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="counter">Counter</div> <div id="button">Click to add 1</div> <div id="changed">This must turn red when counter > 5</div>

Each of these assigns a click event to the button element.这些中的每一个都会为button元素分配一个click事件。 Then it's a matter of examining the count variable each time the button is clicked and using a conditional statement to perform the change.然后就是在每次单击按钮时检查count变量并使用条件语句来执行更改。

If you have many buttons, move the details to their own function so each button can call the function.如果你有很多按钮,将详细信息移动到自己的 function 这样每个按钮都可以调用 function。

function updateCount(){
  $("#counter").html("Counter: " + ++count + "/30");
  if (count > 5) {
    $("#changed").css("color", "red");
  }
}

The click callback can just call this function from any button. click回调可以从任何按钮调用此 function。

$("#button").click(updateCount);

Or要么

document.getElementById("button").addEventListener("click", updateCount);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM