开发者

anchor tag with JavaScript, inside JavaScript

开发者 https://www.devze.com 2023-01-23 03:23 出处:网络
I have JavaScript that outputs links (search results) but I\'m having problems adding onclick in the anchor tag

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(&#39;http://www.akademika.no/node/"+item.link+"&#39;)'>" + item.title + "</a>"; 

I've replaced two apostrophes with &#39; inside your string.

Also, don't you mean $('#bokvisning_content').load ..., which would give us:

var str = "<a href='#bokvisning' onclick='javascript:$(&#39;#bokvisning_content&#39;).load(&#39;http://www.akademika.no/node/"+item.link+"&#39;)'>" + item.title + "</a>"; 

All in all, using @Nick Craver's solution to untangle the multiple layers of quoting might be best.

0

精彩评论

暂无评论...
验证码 换一张
取 消