Reputation: 1384
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
Upvotes: 1
Views: 905
Reputation: 6565
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>`
Upvotes: 4
Reputation: 4021
You need to append onclick to your element txt.onclick="goToUrl(' + url + ');
Upvotes: 0
Reputation: 1472
Change to this:
onclick="goToUrl(' + url + '); return false;"
That will prevent the action of the browser.
Upvotes: 0