在這裏,我們有一個onclick處理一個div:HTML中支持內嵌JavaScript事件子標記嗎?
<div id="BorderContainer1282" onclick="alert('hello')">
<input id="Button925" type="button" value="Button">
</div >
當點擊它顯示一個警告對話框。
不支持HTML內嵌JavaScript同名的子標籤,就像這樣:
<div id="BorderContainer1282">
<onclick>alert('hello');</onclick>
<input id="Button925" type="button" value="Button">
</div >
這個問題是不是最好的做法。具體來說,HTML支持在HTML元素的子標記中設置事件,如示例中所示。
注意:我在示例2中測試了上面的代碼,它在我的測試中不起作用。
如果它不能正常工作,會使用以下模板是一個可以接受的選擇:
<div id="BorderContainer1282">
<script type="text/javascript">
document.getElementById('BorderContainer1282').addEventListener("click", function(event) {
(function(event) {
alert('hello');
}).call(document.getElementById("BorderContainer1282"), event);
});
</script>
<input id="Button925" type="button" value="Button">
</div >
同樣,我現在不擔心最佳實踐,只有在支持此功能。
我發現了一個類似的問題here這不是重複的。
''標籤?作爲一個屬性,它已經很醜陋,但是...... Ps:從來沒有在HTML中看到過這個,但也許很久很久以前? PPs:你最近的例子中'call()'的用途是什麼? –
Kaiido
我認爲這個調用導致'this'引用引用HTML元素而不是另一個對象。 –
錯誤的猜測,'this'指的是事件已附加到的對象。在這裏你調用'undefined'(addEventListener()')的結果) – Kaiido