Javascript 在下一个函数中使用变量from选项
我试图解决从选项中获取值的问题。 当我从select中选择一个数字时,该数字在p tag中正确打印,let index也正确,但我想在本程序的下一个函数中使用“const n”。为了进行测试,我创建函数send()进行检查,我可以使用这个变量,但所有时间console.log都是NaN。我怎样才能解决这个问题Javascript 在下一个函数中使用变量from选项,javascript,select,option,Javascript,Select,Option,我试图解决从选项中获取值的问题。 当我从select中选择一个数字时,该数字在p tag中正确打印,let index也正确,但我想在本程序的下一个函数中使用“const n”。为了进行测试,我创建函数send()进行检查,我可以使用这个变量,但所有时间console.log都是NaN。我怎样才能解决这个问题 <p id="p">Your number is: 0</p> <select id="select"> <option>1</
<p id="p">Your number is: 0</p>
<select id="select">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button onclick="send();">SEND</button>
//JS
var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')
const n = selectElem.addEventListener('change', function() {
let index = selectElem.value;
pElem.innerHTML = 'Your number is: ' + index;
return index;
})
console.log(n);
const a = n*2;
function send(){
console.log('-----');
console.log(n);
console.log(a);
}
您的号码是:0
1.
2.
3.
4.
5.
发送
//JS
var selectElem=document.getElementById('select'))
var pElem=document.getElementById('p')
const n=selectElem.addEventListener('change',function()){
让index=selectElem.value;
pElem.innerHTML='您的号码是:'+索引;
收益指数;
})
控制台日志(n);
常数a=n*2;
函数send(){
console.log('----');
控制台日志(n);
控制台日志(a);
}
第二个参数(函数)是回调。
此外,您还可以使用窗口
,获取所需的对象
var a=10
function send(){
console.log('-----');
console.log(window.n);
console.log(window.a);
}
而且,JS是基于原型的语言。所以,我怀疑它与类
有什么关系。(从语法上来说,可能是这样)您可以创建一个函数setN并将其校准以更新object.n。。看我的例子
//JS
var selectElem=document.getElementById('select'))
var pElem=document.getElementById('p')
var obj={
n:‘weqwe’
}
函数集n(n){
对象n=n
}
选择Elem.addEventListener('change',函数(obj){
让index=selectElem.value;
setN(选择元素值);
pElem.innerHTML='您的号码是:'+索引;
收益指数;
})
函数send(){
console.log(对象号)
}
JS-Bin
您的号码是:0
1.
2.
3.
4.
5.
发送
您无法访问函数范围内的变量。为此,必须创建一个类,该类应包含所有变量和所需函数。