我试图从元素'amt1'中获取值,每次单击按钮并将其显示在元素'pro1'中时,该值都会增加。但是,我收到的值“ undefined”对JavaScript来说真的很新。希望有人可以帮助我。预先谢谢你!
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
var price1 = document.getElementById("amt1").value;
return price1;
};
}(0);
var total1 = price1*parseFloat(119.90);
function displayPrice(){
document.getElementById('pro1').innerHTML = total1;
}
答案 0 :(得分:1)
price1
是sum
函数返回的函数的词法范围内的局部变量。当您尝试将其乘以119.90
时,它的值在外部范围中不可用。
您可以改为从amt1
函数内部的元素displayPrice
中获取价格。
如果amt1
元素不是input
,则应该使用元素的.textContent
属性而不是.value
:
var add1 = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
};
}(0);
document.querySelector('button').addEventListener('click', add1)
function displayPrice(){
var price = parseFloat(document.getElementById("amt1").textContent);
var total = price * 119.90;
document.getElementById('pro1').innerHTML = total;
}
document.querySelectorAll('button')[1].addEventListener('click', displayPrice)
<p id="amt1">0</p>
<button>Add</button>
<br><br>
<button>Total</button>
<p id="pro1"><p>