简体   繁体   中英

Call function only once Javascript

I created a radio button where the user can select either Metric or Imperial units. The following code is the event handler:

var metricRadio = document.getElementById("metric");
var imperialRadio = document.getElementById("imperial");

metricRadio.addEventListener("click", toMetric, false);

imperialRadio.addEventListener("click", toImperial, false);

When the user clicks the Metric radio button the function toMetric is called. In the function toMetric I convert what the user entered in Imperial to Metric and I update the input boxes with the Metric values. The problem is that if Metric is selected and he clicks the Metric radio button again the function toMetric is called again. How can I prevent calling the toMetric function when the Metric radio button is selected.

You can test what I mean here: JSFiddle

Just enter 3 values and click the Metric or Imperial radio button more than once.

Look at this: jsFiddle .

I used "change" instead of "click":

metricRadio.addEventListener("change", toMetric, false);

imperialRadio.addEventListener("change", toImperial, false);

您应该添加一个包含当前状态(公制或英制)的变量,并在您的函数中使用if条件测试当前状态,而不是尝试仅一次调用一个函数(您可以设置变量)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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