内联 JavaScript 触发器不起作用

inline javascript trigger doesn't work

本文关键字:不起作用 触发器 JavaScript 内联      更新时间:2023-09-26
html = '<a href="#" onclick="alert("This link is clickable only in the mobile!")">text</a>'

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

您需要

转义属性值中的"字符...使用&quot;特殊实体:

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

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

j查询:

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(&quot;This link is clickable only in the mobile!&quot;)">text</a>'

您可以在锚点的href中直接附加javascript方法,还需要编码(转义(引号。