2015-09-18 46 views
0
html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>' 

我附加了我的html,但是当我点击它说意外的令牌},是不可能做这样的内联触发器?内嵌javascript触发器不起作用

+0

问题在于引号嵌套,在警报中使用'' – Tushar

+0

我建议您不要使用内联处理程序,使用'addEventListener'来绑定事件 – Tushar

回答

4

你一定要逃逸属性值"字符...使用&quot; special entity

html = '<a href="#" onclick="alert(&quot;This link is clickable only in the mobile!&quot;)">text</a>' 

有更好的选择来实现,而不是用JavaScript编写原始的HTML这一点。

jQuery

var aElement = jQuery("<a>").attr("href", "#").click(function() { 
    alert("This link is clickable only in the mobile!"); 
}); 
// You can append it like: 
aElement.appendTo(document.body); 

纯JavaScript:

var aElement = document.createElement("a"); 
aElement.setAttribute("href", "#"); 
// If you want the onclick attribute to show up in HTML source: 
aElement.setAttribute("onclick", "alert(\"This link is clickable only in the mobile!\")"); 
// This way is easier: 
aElement.onclick = function() { 
    alert("This link is clickable only in the mobile!"); 
} 
// Append like: 
document.body.appendChild(aElement); 
3

这是不可能完全一样的,因为你是混合双引号。

使用一个转义单引号的字符串中:

html='<a href="#" onclick="alert(\'This link is clickable only in the mobile!\')">text</a>' 
1
html = '<a href="javascript:alert(&quot;This link is clickable only in the mobile!&quot;)">text</a>' 

可以directcly附加JavaScript方法在锚的href还需要进行编码(转义)的报价。