如何将此 段代码中的numvalue4拿出来用,并且在函数中numvalue4随着点击按钮变化,函数外的numvalu4也跟着变化var minus = document.querySelector(".nummbe #minus"); minus.onclick = function(){ var numvalue4=document.getElementById("nummbe-value").value; numvalue4 = parseInt(numvalue4); numvalue4=numvalue4-1; if (numvalue4<0){ numvalue4=0; } document.getElementById("nummbe-value").value = numvalue4; var numpr = document.getElementById("numprice"); numpr.innerHTML=(34.99*numvalue4); } var minus = document.querySelector(".nummbe #plus"); minus.onclick = function(){ var numvalue4=document.getElementById("nummbe-value").value; numvalue4 = parseInt(numvalue4); numvalue4=numvalue4+1; document.getElementById("nummbe-value").value = numvalue4; var numpr = document.getElementById("numprice"); numpr.innerHTML=(34.99*numvalue4); }
时间: 2024-03-26 09:35:25 浏览: 71
可以将numvalue4定义为全局变量,这样就可以在函数内外都使用了。代码如下:
```
var numvalue4 = 0; // 定义全局变量
var minus = document.querySelector(".nummbe #minus");
minus.onclick = function(){
numvalue4 = parseInt(document.getElementById("nummbe-value").value);
numvalue4=numvalue4-1;
if (numvalue4<0){
numvalue4=0;
}
document.getElementById("nummbe-value").value = numvalue4;
var numpr = document.getElementById("numprice");
numpr.innerHTML=(34.99*numvalue4);
}
var plus = document.querySelector(".nummbe #plus"); // 修复变量名错误
plus.onclick = function(){
numvalue4 = parseInt(document.getElementById("nummbe-value").value);
numvalue4=numvalue4+1;
document.getElementById("nummbe-value").value = numvalue4;
var numpr = document.getElementById("numprice");
numpr.innerHTML=(34.99*numvalue4);
}
```
这样就可以在函数内部使用numvalue4,并且当点击按钮时,numvalue4会随之变化。同时,函数外的numvalue4也会跟着变化,因为它是全局变量。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)