How to use a variable script? JS

Asked

Viewed 148 times

0

I’m looking to create a custom Javascript:

Ex:

var lx = function(addr){window.open(addr, '_self'); }

But it didn’t work.

I used up to visual studio 2012 to edit this script but html did not recognize the function

lx('www.google.com');
  • You are running these codes in sequence and in the same file?

  • There’s nothing wrong with it, see jsFiddle. How/where you are calling lx? What your Chrome Inspector is claiming?

  • Why I tested it here on the Chrome console and the only change I made to work was to add http:// to the address. And it worked.

  • Are you calling this code on what part of the file? If it is in an HTML file it has to be within the tag script.

  • @user12138, your variable usage is correct. That is, you are passing a value correctly into the function. What is unclear is what you want to do with window.open. You can explain better?

1 answer

2

HTML

<button id="open">Clique aqui</button>

JAVASCRIPT

function open (address) {
    window.open(address, '_blank');
};

var button = document.getElementById('open');

button.addEventListener('click', function () {
    open('http://google.com');
});

And also don’t forget to put the http at the beginning of the link, as it can be interpreted as a folder.

DEMO, Thanks @Guilherme Oderdenge

For your method to work, the code must be executed in the same file.

HTML + JAVASCRIPT

<html>
<head>
   /* CSS, SCRIPTS, ETC.... */
  <script type="text/javascript">
       var lx = function(addr){ window.open(addr, '_self'); }
  </script>
</head>
<body>
  <script type="text/javascript">
      lx("http://www.google.com");
  </script>
</body>
</html>

Another option is to use window.location if you want to open in the same window/tab

var lx = function(addr){ window.location = addr; }
  • Your answer makes no sense because there is no error to base it on. The _self will open a window in the same frame that was clicked on and the chances of it working are greater than using the _blank. Therefore, I have denied. Invalid answer.

  • the lx(addr) function appears that it does not exist.

  • 1

    @user12138 I did this jsFiddle for you. Give it a try - there is no reason to go wrong. And Diego, I did not pay attention to your tip http as suffix - if possible, edit your question and I will remove my -1.

  • @Guilhermeoderdenge updated code, my fault, the same problem is why was trying to access from Jsfiddle google in iframe, sorry!

  • @Diegoviera It happens, man! Now your negative has turned into a positive! + 1! :D

Browser other questions tagged

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