(Javascript-jQuery) Variables within variables giving "Undefined"

Asked

Viewed 1,813 times

1

Hello.

I have this code that is failing to capture this variable.

HTML, attempt 1:

<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="funcao()">Clique aqui!</a></p>
    </body>
</html>

Javascript (with jQuery), try 1:

var link;
var testando="Testando essa <a href=\""+link+"\">variável</a> aqui.";
function funcao(){
    link="http://www.google.com";
    $('p').html(testando);
}

HTML, trial 2:

<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="funcao('www.google.com')">Clique aqui!</a></p>
    </body>
</html>

Javascript (with jQuery), trial 2:

var link;
var testando="Testando essa <a href=\""+link+"\">variável</a> aqui.";
function funcao(link){
    $('p').html(testando);
}

In neither of the two, the variable "link" is received, with the value "Undefined" (undefined).

This is the initial way it works (but I’m optimizing):

Try HTML 1;

Javascript (with jQuery):

var link;
var testandoi="Testando essa <a href='";
var testandoii="'>variável</a> aqui.";
function funcao(link){
    $('p').html(testandoi+link+testandoii);
}

I find it totally unnecessary to declare two variables for one sentence.

If anyone has a solution, I thank you.

  • Try to pass the variable when calling the function, without creating the "var link". JS can understand that it is a local variable and does not return the desired.

3 answers

3


Thiago, I believe you are having some problem understanding the scope of a variable and the unchanging nature of a string.

when you are concatenating strings, you are not joining the reference of the strings, but a copy of their values.

then when doing the following:

var testando="Testando essa <a href=\""+link+"\">variável</a> aqui.";

you are making a copy of the link variable at that time.

to get the result you expect without modifying your code too much, you need to turn the variable testing into a method.

var link;
var getTestando = function () {
  return "Testando essa <a href=\"" + link + "\">variável</a> aqui.";
}
function funcao(){
    link = "http://www.google.com";
    $('p').html(getTestando());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a onclick="funcao()">Clique aqui!</a></p>

And as suggested by Oeslei, the simplest way would be as follows:

function funcao(link){
    $('p').html("Testando essa <a href=\"" + link + "\">variável</a> aqui.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a onclick="funcao('http://www.google.com')">Clique aqui!</a></p>

  • 2

    Even simpler would be to use the variable link as a parameter. It would eliminate a global variable, decrease an unnecessary line in the function call and prevent code debugging from getting complicated at some point by some script changing the variable link.

  • 1

    @Oeslei, for sure this would be the best way, but I also did not understand why he tried to complicate so much, maybe I was trying to do it in some exotic way.

1

The problem you have in example 1 is good to explain what is failing you. When you have:

var link;
var testando="Testando essa <a href=\""+link+"\">variável</a> aqui.";
function funcao(){
    link="http://www.google.com";
    $('p').html(testando);
}

and flames the function funcao() the variable testando is already closed. That is, from the moment that line var testando="Testando essa <a href=\""+link+"\">variável</a> aqui."; runs that its value is "closed".

What you want is for that variable to be completed only when you run a function. There you are thinking correctly in your last example. In that case you have a function that when called takes as argument the missing piece link and then you can create the final string at the right time.

Note however that in this case it is irrelevant to have the variable link defenida in the previous scope because when you give a variable name as an argument of a function it creates new scope. For example:

var link = 'foo';
function fn(link){
    alert(link);
}

fn('lalala'); // o alert vai dar "lalala" e não "foo"

So your job could just be:

var testandoi = "Testando essa <a href='";
var testandoii = "'>variável</a> aqui.";

function funcao(link) {
    $('p').html(testandoi + link + testandoii);
}

But if I understand what you need is to know the link that was clicked? then you can have it in HTML:

<p><a href="http://google.com" onclick="funcao(event)">Clique aqui!</a></p>

and acts function to fetch the link to event.target which points to the <a>that was clicked:

function funcao(e) {
   e.preventDefault(); // junta esta linha para impedir que o link faça navegar para outra página
   var link = e.target.href;
   alert(link);
}

Example: https://jsfiddle.net/vLy1x8ke/

0

If you want to keep the replacement string as an external resource to the function, you can use it outside and replace the value dynamically using the function String.format (there is no native, so I created a version, based in that)

String.format = function() {
  // The string containing the format items (e.g. "{0}")
  // will and always has to be the first argument.
  var theString = arguments[0];

  // start with the second argument (i = 1)
  for (var i = 1; i < arguments.length; i++) {
    // "gm" = RegEx options for Global search (more than one instance)
    // and for Multiline search
    var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
    theString = theString.replace(regEx, arguments[i]);
  }

  return theString;
}

var patternTest = "Testando essa <a href=\"{0}\">variável</a> aqui."

function funcao(link) {
  $('p').html(String.format(patternTest, link));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><a onclick="funcao('http://www.google.com')">Clique aqui!</a>
</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.