(JavaScript-jQuery) Variables within variables giving "undefined"

1

Hello.

I have this code that is not able to capture this variable.

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

JavaScript (with jQuery), try 2:

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

In either case, the variable "link" is received, with the value "undefined".

This is the initial form that works (but I'm optimizing):

Try 1 HTML;

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 a single sentence.

If someone has a solution, thank you in advance.

    
asked by anonymous 20.03.2015 / 17:16

3 answers

3

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

When you are concatenating strings, you are not putting together their reference, 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 changing your code very much, you need to transform the test variable 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><aonclick="funcao()">Clique aqui!</a></p>

And as suggested by Oeslei, the simplest form 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><aonclick="funcao('http://www.google.com')">Clique aqui!</a></p>
    
20.03.2015 / 17:44
1

The problem you have in example 1 is good for explaining 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 you call the function funcao() the variable testando is already defined. 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 this variable to be completed only when you run a function. Then you are thinking correctly in your last example. In this case you have a function that when called takes as an argument the missing piece link and there can create the final string at the right time.

Note however that in this case it is irrelevant to have the variable link defined in the previous scope because when giving a variable name as an argument to a function it creates a 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 role could only be:

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

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

But if I understood correctly what you need to know the link that was clicked? so you can have it in HTML:

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

and it acts to fetch the link to event.target that points to the <a> element 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: link

    
21.03.2015 / 00:00
0

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

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><aonclick="funcao('http://www.google.com')">Clique aqui!</a>
</p>
    
20.03.2015 / 18:36