[英]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. 当用户单击“度量”单选按钮时,将调用toMetric
函数。 In the function toMetric
I convert what the user entered in Imperial to Metric and I update the input boxes with the Metric values. 在toMetric
函数中,我将用户在Imperial中输入的内容转换为Metric,并使用Metric值更新输入框。 The problem is that if Metric is selected and he clicks the Metric radio button again the function toMetric
is called again. 问题在于,如果选择了“度量标准”,然后他再次单击“度量标准”单选按钮, toMetric
再次调用toMetric
函数。 How can I prevent calling the toMetric
function when the Metric radio button is selected. 选择“度量”单选按钮时,如何防止调用toMetric
函数。
You can test what I mean here: JSFiddle 您可以在这里测试我的意思: JSFiddle
Just enter 3 values and click the Metric or Imperial radio button more than once. 只需输入3个值,然后多次单击“公制”或“英制”单选按钮。
您应该添加一个包含当前状态(公制或英制)的变量,并在您的函数中使用if条件测试当前状态,而不是尝试仅一次调用一个函数(您可以设置变量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.