内联javascript触发器不';行不通 html=''

内联javascript触发器不';行不通 html='',javascript,jquery,Javascript,Jquery,我附加了我的html,但当我单击它时,它显示意外标记},是否不可能这样执行内联触发器?您需要转义属性值中的“字符…使用: 这不可能完全像那样,因为你混合了双引号 在字符串中使用转义单引号: var aElement = document.createElement("a"); aElement.setAttribute("href", "#"); // If you want the onclick attribute to show up in HTML source: aElement.se

我附加了我的html,但当我单击它时,它显示意外标记},是否不可能这样执行内联触发器?

您需要转义属性值中的
字符…使用:


这不可能完全像那样,因为你混合了双引号

在字符串中使用转义单引号:

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);
html=''
html=''

您可以直接在anchor的
href
中附加javascript方法,还需要对引号进行编码(转义)。

问题在于引号嵌套,在警报中使用\',我建议您不要使用内联处理程序,使用
addEventListener
绑定事件
html = '<a href="#" onclick="alert(&quot;This link is clickable only in the mobile!&quot;)">text</a>'
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);
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);
html='<a href="#" onclick="alert(\'This link is clickable only in the mobile!\')">text</a>'
html = '<a href="javascript:alert(&quot;This link is clickable only in the mobile!&quot;)">text</a>'