1

I'm writing html in Javascript using innerHTML, in one case, I'm appending a href tag like so :

txt.innerHTML += '<a href="" id="rssLinks" onclick="goToUrl(' + url + ');">Read more</a>';

where url is a string containing a url.

And the goToUrl function looks like as follows :

    function goToUrl(urlToBrowse) {
       window.open(urlToBrowse, "_blank");
    }

But my onclick never gets called, can anyone see the problem? Cheers

1
  • hint: alert your string. Commented Feb 12, 2014 at 10:45

3 Answers 3

4

try this

txt.innerHTML += "<a href='' id='rssLinks' onclick='alert(\"" + url + "\");'>Read more</a>";
//........................................................^............^ 
//.............................................................may needed

because call would look like goToUrl(http://google.com)

and that's a string so it has to be goToUrl("http://google.com")

EDIT 01/2020 - "New" way to add this parameter

Since ES6, you can write it with a Template-String

txt.innerHTML += `<a href='' id='rssLinks' onclick='goToUrl("${url}");'>Read more</a>`
Sign up to request clarification or add additional context in comments.

5 Comments

Hi, I'm trying this, but I have a problem, I alerted my string before quotes, and it looks like as follows : goToUrl(test.com/content......); and then after I tried to add the surrounding strings as you showed, it looks like this : goToUrl("http:="" www.test.com="" content="" ....);
I tried with turned quotes but the url still becomes malformed
now... :D try and error but this should work now! ^^
Hi, just one more small problem - it looks fine in the alert, but now there are html "&quot" surrounding the link and my function doesn't get called
guess you have a function like php htmlentities ? may innerHTML forms it like this...
0

Change to this:

onclick="goToUrl(' + url + '); return false;"

That will prevent the action of the browser.

Comments

0

You need to append onclick to your element txt.onclick="goToUrl(' + url + ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.