在Javascript中将函数值传递给其他函数 [英] Pass a value from function to other functions in Javascript
问题描述
我需要从javascript函数中的HTML输入中获取值。我可以成功地从HTML中获取值,但我无法将其从1个函数传递给其他函数。我需要将该值传递给该javascript上可用的其他函数。我尝试了这段代码我未定义。
I need to get a value from an HTML input in a javascript function. I can successfully get the value form the HTML but I couldn't pass that from 1 function to other. And I need to pass that value to other function that is available on that javascript. I tried this code I'm getting undefined.
这是我的HTML代码:
This is my HTML code:
<input value="3232" id="fn">
这是我的主要功能脚本,我可以从HTML中获取值:
This is my script with the main function, and I can get the value from the HTML:
var PageKey = function(){
var val = document.getElementById('demo').value
}
var fun1 = function(data){
}
var fun2 = function(data){
}
var fun3 = function(data){
}
这就是我的尝试:
var fun3 = function(data){
PageKey();
}
推荐答案
PageKey()
只是获取值,但它不会返回它。因此,您需要将 return val;
添加到 PageKey()
。然后,在fun3中,您可以将变量设置为从 PageKey()
返回的变量。所以,你最终得到这个:
PageKey()
is just getting the value, but it does not return it. So, you need to add return val;
to PageKey()
. Then, in fun3, you can set a variable to what's returned from PageKey()
. So, you would end up with this:
var PageKey = function(){
var val = document.getElementById('demo').value;
return val;
}
var fun1 = function(data){
}
var fun2 = function(data){
}
var fun3 = function(data){
var val = PageKey();
console.log(val);
// prints out what PageKey got
fun1(val);
fun2(val);
}
这篇关于在Javascript中将函数值传递给其他函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!