html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>'
我附加了我的html,但是当我点击它说意外的令牌},是不可能做这样的内联触发器?内嵌javascript触发器不起作用
html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>'
我附加了我的html,但是当我点击它说意外的令牌},是不可能做这样的内联触发器?内嵌javascript触发器不起作用
你一定要逃逸属性值"
字符...使用"
special entity:
html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>'
有更好的选择来实现,而不是用JavaScript编写原始的HTML这一点。
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);
这是不可能完全一样的,因为你是混合双引号。
使用一个转义单引号的字符串中:
html='<a href="#" onclick="alert(\'This link is clickable only in the mobile!\')">text</a>'
html = '<a href="javascript:alert("This link is clickable only in the mobile!")">text</a>'
可以directcly附加JavaScript方法在锚的href
还需要进行编码(转义)的报价。
问题在于引号嵌套,在警报中使用'' – Tushar
我建议您不要使用内联处理程序,使用'addEventListener'来绑定事件 – Tushar