[英]Get variable outside scope from a function inside an object - Javascript
[英]How to get variable outside from inside the function
我有开发区域计算器功能,但在这里我面临一个问题。 我在 function 内得到总计,现在我想在 function 之外使用这个总计值。 我已经像这样在外面声明了 var total = 0 total1 = 0 Total = 0 Total1 = 0; 当我调用这些变量时,我得到的只是零。 我没有从 function 得到任何东西。 我如何将 function 内部的值调用到外部。 对于参考,请找到我的以下代码。
<select
name="unit"
class="areacalc-select"
data-bind="options: $parent.unitsArray, value: selectedUnit"
>
<option value="m">m</option>
<option value="mm">mm</option>
<option value="cm">cm</option>
<option value="inches">inches</option>
<option value="feet">feet</option>
</select>
var 总计 = 0,总计 = 0,
$("#areaWidth,#areaHeight").keyup(function () {
var textValue1 = $("#areaWidth").val();
var textValue2 = $("#areaHeight").val();
total = textValue1 * textValue2;
document.getElementById("total").innerHTML = total;
document.getElementById("totalvalue").innerHTML = total;
$(document).ready(function () {
$(".areacalc-select").on("change", function () {
var measurement = document.querySelector(".areacalc-select").value;
console.log(measurement);
if (measurement === "m") {
Total = total;
document.getElementById("total").innerHTML = Total;
document.getElementById("totalvalue").innerHTML = Total;
} else if (measurement === "mm") {
Total = total * 3;
document.getElementById("total").innerHTML = Total;
document.getElementById("totalvalue").innerHTML = Total;
} else if (measurement === "cm") {
Total = total * 4;
document.getElementById("total").innerHTML = Total;
document.getElementById("totalvalue").innerHTML = Total;
} else if (measurement === "inches") {
Total = total * 5;
document.getElementById("total").innerHTML = Total;
document.getElementById("totalvalue").innerHTML = Total;
} else {
Total = total * 6;
document.getElementById("total").innerHTML = Total;
document.getElementById("totalvalue").innerHTML = Total;
}
console.log(typeof Total);
});
});
});
document.getElementById("area-calc-total").innerHTML = Total;
你不能直接。
在 JavaScript 中,函数内部声明的变量是 scope 有界的。
如果要使用在 function 中声明的变量,请返回该值。 如果要返回多个值,请将它们放入 object 并返回 object。
If you want to do it in a more interesting way, check closures in JavaScript, where the parent variable is accessible to child function, so you can wrap child function inside of parent function.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.