I have JavaScript that outputs links (search results) but I'm having problems adding onclick in the anchor tag
var str = "<a href='#bokvisning' onclick='javascript:$(#bokvisning_content).load('http://www.akademika.no/node/"+item.link+"')'>" + item.title + "</a>";
It outputs this, which is wrong:
<a href="#bokvisning" onclick="javascript:$(#bokvisning_content).load(" http:="" www.akademika.no="" node开发者_JS百科="" link')'="">Title</a>`
Is it possible? What other options do I have?
The quick fix is the quotes, like this:
var str = "<a href='#bokvisning' onclick='javascript:$(\'#bokvisning_content\').load(\'http://www.akademika.no/node/"+item.link+"\')'>" + item.title + "</a>";
It would be better to add the click handler unobtrusively though, like this:
var anchor = $("<a/>", {href:'#bokvisning', text:item.title}).click(function() {
$("#bokvisning_content").load("http://www.akademika.no/node/"+item.link);
});
//or for older jQuery versions (<1.4):
var anchor = $("<a href='#bokvisning'></a>").text(item.title).click(function() {
$("#bokvisning_content").load("http://www.akademika.no/node/"+item.link);
});
Then append that to whatever element you're currently putting the string in.
Note: The second option above assumes jQuery is an option because your onclick
is using it.
You have to properly escape the quotes:
var str = "<a href='#bokvisning' onclick='javascript:$(#bokvisning_content).load('http://www.akademika.no/node/"+item.link+"')'>" + item.title + "</a>";
I've replaced two apostrophes with '
inside your string.
Also, don't you mean $('#bokvisning_content').load ...
, which would give us:
var str = "<a href='#bokvisning' onclick='javascript:$('#bokvisning_content').load('http://www.akademika.no/node/"+item.link+"')'>" + item.title + "</a>";
All in all, using @Nick Craver's solution to untangle the multiple layers of quoting might be best.
精彩评论