I am trying to create an anchor link when a user clicks on another link.
When I click on the first link, the onclick event is raised and generates another link using JavaScript, but that is not generated properly.
This is my anchor link in JavaScript:
temp="<li><a href='#' onclick='showMenu3('"+menu2[0]+"','"+menu2[2]+"')'>
<img src='images/noImageSmall.png'/>"+menu2[2]+"</a></li>";
But it is generated in the source as following:
<li><a href="#" onclick="showMenu3(" 139','invite="" a="" friend')'="">
<img src="images/noImageSmall.png">Invite a friend</a></li>
How can I generate the following link using JavaScript?
<li><a href="#" onclick="showMenu3('139','invite friend')">
<img src="images/noImageSmall.png">Invite a friend</a></li>
This will work:
Not surprisingly, I agree with the others that this is not a good practice. It’s error-prone, way too easy to generate invalid markup (which will introduce more bugs down the line) and you have to really understand string concatenation.
My preferred method is this:
Here’s a fiddle demonstrating both techniques: http://jsfiddle.net/mLrbP/
Use a DOM inspector to see the markup generated.