2

我正在使用原型1.7.0。 我有一個像下面提到的標籤的HTML代碼。 我已經添加了一個自定義的方法。現在html標記的自定義屬性不被ie9和firefox識別

<div id="showButton" onclick="javascript:hello();" onhide="onNamehide()">show</div> 

當我點擊,$('showButton').onhide計算結果爲true顯示在IE8和IE9中,Firefox的錯誤。

function hello(){ 
    if($('showButton').onhide){ 
    alert("I am able to find onhide function"); 
    } else { 
    alert("Sorry, I am not able to find onhide function"); 
    } 
} 

有人可以向我解釋這個嗎?

+0

'Prototype'不是jquery。錯誤的標籤名稱! – 2012-01-09 17:44:16

回答

3

Element#hasAttribute

if ($('showButton').hasAttribute('onhide')) { 

的原因,測試onhide只是有時工作是複雜和微妙。從技術上講,$('showButton')返回的對象是DOM的JavaScript表示,它本身不是HTML元素。舊的瀏覽器會將HTML屬性視爲DOM屬性來混淆問題,但設置DOM屬性並不總是設置HTML屬性。隨着瀏覽器越來越接近規範,差異變得更加準確。

嘗試通過使用像getAttributesetAttribute(在原型抽象爲readAttributewriteAttribute跨browserness起見)函數編寫代碼來規範,而不是實現。