在這裏,我試圖定義一個名爲zerg
的HTML屬性,並在點擊段落時顯示它,但是當它被點擊時顯示「undefined」。 the code that I've written有什麼問題,以及正確的方法是什麼?設置HTML元素內嵌屬性
<p onclick = "alert(this.zerg);" zerg = "Why doesn't this work?">Click here!</p>
在這裏,我試圖定義一個名爲zerg
的HTML屬性,並在點擊段落時顯示它,但是當它被點擊時顯示「undefined」。 the code that I've written有什麼問題,以及正確的方法是什麼?設置HTML元素內嵌屬性
<p onclick = "alert(this.zerg);" zerg = "Why doesn't this work?">Click here!</p>
爲了兼容HTML5,屬性應該被命名爲data-zerg
代替zerg
。試試這個:
<p onclick = "alert(this.getAttribute('data-zerg'));" data-zerg = "Now it works as intended!">Click here!</p>
+1用於指定html的有效性...... – PSL 2013-05-11 02:13:09
關於你的答案......在你問這個問題之前,你是否知道這一點? – 2013-05-11 03:00:33
@squint不,我問這個問題,因爲我還沒有找到解決方案。 – 2013-05-11 03:15:15
試試這個:
<p onclick = "alert(this.getAttribute('zerg'));" zerg = "Why doesn't this work?">Click here!</p>
您可以使用getAttribute()
方法:
<p onclick = "alert(this.getAttribute('zerg'));" zerg = "Why doesn't this work?">Click here!</p>
你可以試試這個: -
<p onclick = "javascript:alert(this.getAttribute('zerg'));" zerg="Now it works as
intended!">Click here!</p>
this
參考當前元素。因此,您可以使用this.getAttribute()
作爲內嵌代碼。
屬性與屬性不同。 'this.getAttribute(「zerg」);'雖然它不是一個有效的屬性。您可以使用'data-zerg'至少符合HTML5。 – 2013-05-11 01:51:56
作爲一個小背景閱讀:http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice和http://en.wikipedia.org/wiki/Unobtrusive_JavaScript – Xotic750 2013-05-11 01:56:14
「Unobtrusive JavaScript」是一種宗教信仰。 – 2013-05-11 01:57:58