javascript:在另一个函数中获取函数的变量值 [英] javascript: get a function's variable's value within another function

查看:148
本文介绍了javascript:在另一个函数中获取函数的变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < input type =textvalue =hahaid = FULL_NAME/> 

脚本中的这段代码

 < script language =javascripttype =text / javascript> 
函数first(){
var nameContent = document.getElementById('full_name')。value;


函数second(){
first();
y = nameContent;
alert(y);
}
秒();
< / script>

我想要一个显示元素full_name的值的警报,但它似乎不起作用,有谁知道为什么? :S

解决方案

nameContent 只存在于 first()函数,正如您在 first()函数中定义的那样。



<为了使其作用域更广泛,请在函数之外定义它:

  var nameContent; 

函数first(){
nameContent = document.getElementById('full_name')。value;


函数second(){
first();
y = nameContent;警报(Y);
}
秒();

稍好的方法是 return 这个值,因为全局变量非常快速地变得混乱:

pre $函数getFullName(){
return document.getElementById(' 。FULL_NAME')值;


函数doStuff(){
var name = getFullName();

alert(name);
}

doStuff();


okay so I have this code in body:

<input type="text" value="haha" id="full_name"/>

And this code in script

<script language="javascript" type="text/javascript">
    function first(){
        var nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

I want a alert showing the value of the element full_name, but it doesn't seem to work, does anyone know why? :S

解决方案

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();

这篇关于javascript:在另一个函数中获取函数的变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆