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