简体   繁体   English

带有 JavaScript 的锚标记,在 JavaScript 中

[英]anchor tag with JavaScript, inside JavaScript

I have JavaScript that outputs links (search results) but I'm having problems adding onclick in the anchor tag我有输出链接(搜索结果)的 JavaScript,但我在锚标记中添加 onclick 时遇到问题

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="" 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.注意:上面的第二个选项假设 jQuery 是一个选项,因为您的onclick正在使用它。

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;我用&#39;替换了两个撇号inside your string.在你的字符串里面。

Also, don't you mean $('#bokvisning_content').load ... , which would give us:另外,你不是说$('#bokvisning_content').load ... ,这会给我们:

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.总而言之,使用@Nick Craver 的解决方案来解开多层引用可能是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM