简体   繁体   English

如何将局部变量值从一个函数传递给另一个函数?

[英]How do I pass local variable value from one function to another?

In my script I have 2 functions. 在我的脚本中,我有2个功能。 First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element; 第一个函数引用一个div元素,在div内创建一个段落元素,并将一些文本附加到该段落元素中; In my second function is triggered by onclick event attached to a link element. 在我的第二个函数中,是由附加到链接元素的onclick事件触发的。 I want the text in the div to be changed to another text when clicking on the link. 我希望单击链接时将div中的文本更改为另一个文本。 I do realize that there are 2 options how to achieve this: 我确实意识到有两种方法可以实现此目的:

1) declare global variables and use them in my second function; 1)声明全局变量并在我的第二个函数中使用它们; 2) pass the variable value from first function to the second function and manipulkate this value from the second function 2)将变量值从第一个函数传递到第二个函数,并从第二个函数操纵该值

But the question is how to do I correctly pass the variable value from first function to second function: 但是问题是如何正确地将变量值从第一个函数传递给第二个函数:

Here is the code: 这是代码:

<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>

Javascript: 使用Javascript:

window.onload= function createEl(){
    var el = document.createElement('p');
    var x = document.getElementById('box');
    var text = 'text';

    el.appendChild(document.createTextNode(text));
    x.appendChild(el);
}

function change(){
    x.innerHTML="other text";
}

in general you can write this: 通常,您可以这样写:

function one(){
   var var1 = "hello";
   two(var1);
}

function two(x){
   alert(x);
}

this will alert "hello". 这将提醒“你好”。

For what you're doing, I would register my events through code to make it easier to pass a variable. 对于您正在做的事情,我将通过代码注册事件,以使传递变量变得更加容易。 We want to use an argument in the event handling function to pass the data to it. 我们想在事件处理函数中使用一个参数来将数据传递给它。

window.onload = function()
{
    // do your normal stuff with creating elements
    var anc = document.getElementById('ID of your a element here');
    if(anc.attachEvent)
    {
        //code for ancient IE
        anc.attachEvent('onclick', function(){change(x);});
    }
    else if(anc.addEventListener)
    {
        //code for modern browsers
        anc.addEventListener('click', function(){change(x);});
    }
}
function change(elem)
{
    elem.innerHTML='other text';
}

Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. 请注意,较早版本的IE不能识别addEventListener,而是使用attachEvent,如上面的if块所示。 Here's the documentation for addEventListener. 这是addEventListener的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM