javascript - 变量到另一个变量得到 “undefined”

标签 javascript jquery variables scope undefined

在此代码中,变量“link”给出“undefined”。我不知道是什么原因。这是我的代码:

HTML,第一次尝试:

<html>
    <head>
                <meta charset="utf-8" />
        <script src="js.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    </head>
    <body>
        <p><a onclick="doSom()">Click here!</a></p>
    </body>
</html>

JavaScript(带 jQuery),第一次尝试:

var link;
var testing="Testing this <a href=\""+link+"\">variable</a> here.";
function doSom(){
    link="http://www.google.com";
    $('p').html(testing);
}

HTML,第二次尝试:

<html>
    <head>
        <meta charset="utf-8" />
        <script src="js.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    </head>
    <body>
        <p><a onclick="doSom('www.google.com.br')">Click here!</a></p>
    </body>
</html>

JavaScript(带 jQuery),第二次尝试:

var link;
var testando="Testing this <a href=\""+link+"\">variable</a> here.";
function doSom(link){
    $('p').html(testing);
}

变量“link”在上面的代码中没有给出它的值,保持“未定义”。

这是最初的代码,可以工作(但我正在优化它):

第一次尝试的 HTML;

JavaScript(带 jQuery):

var link;
var testingi="Testing this <a href='";
var testingii="'>variable</a> here.";
function doSom(link){
    $('p').html(testingi+link+testingii);
}

我认为完全没有必要为一句话声明 2 个变量。

最佳答案

您的问题归结为这样一个事实:您在初始化之前尝试使用link变量。 p>

var link; // By default, this is `undefined`
var testing="Testing this <a href=\""+link+"\">variable</a> here.";
// Your `testing` link will now contain the string `undefined`
function doSom(){
    link="http://www.google.com";
    // Since you don't update `testing` it still has "undefined" in it somewhere
    $('p').html(testing);
}

解决方案:等到初始化 link 变量后才构建您的测试链接。

关于javascript - 变量到另一个变量得到 “undefined”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171616/

相关文章:

javascript - 我如何从检查元素中知道cpanel中的文件源代码?

javascript - 如何让这个 JavaScript 程序根据提示中的输入来警告对象属性?

javascript - 如何在 jQuery 中解析字符串

jquery - 添加和删​​除类 jQuery

javascript - 你如何确保 Vimeo 视频存在?

javascript - 使用curl登录后获取动态生成的内容

javascript - 即使使用切片,数组的副本也会更改原始数组

arrays - Swift 中的数组返回错误

ruby - 从外部访问类的实例变量

java - "Counter"无法解析为变量错误?