变量转换为另一个“未定义”的变量

Variable into another variable getting “undefined”

本文关键字:未定义 变量 另一个 转换      更新时间:2023-09-26

在这段代码中,变量"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(w/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(w/jQuery),第二次尝试:

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

变量"link"没有在上面的代码中给出其值,仍然是"未定义的"。

这是我的代码,有效(但我正在优化它):

HTML从第一次尝试;

JavaScript(w/jQuery):

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

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

您的问题归结为您试图在初始化之前使用link变量。

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);
}

解决方案:等待建立testing链接,直到初始化了link变量。

在链接有值之前添加链接,因此未定义。然后定义字符串。

请参阅此处:

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

这样做:

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

对于您的代码"tentativa 1",链接未定义的原因是您在为链接分配值之前将其插入到字符串测试中。

更改

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

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

它会起作用的。

与"第二次尝试"相同。移动您的字符串定义进行测试(并将其重命名为正确的),它应该可以正常工作。

我猜"JavaScript(w/jQuery):"工作正常。

不过,您是对的,您不需要定义这些变量。这并不是它在最后一个例子中正确工作的原因。这是因为您在定义"链接"之后才引用它。

一个更好的方法(避免定义无用的变量并在定义后引用"链接")是将您的html赋值更改为如下所示:

    link="http://www.google.com";
    $('p').html("Testing this <a href='""+link+"'">variable</a> here.");

您的主要收获应该是,将变量放入字符串中不会维护对该变量的引用。变量包含在字符串中时的值是最终值。在为其赋值之前,不得将其包含在最终字符串赋值中。