javascript/js對html元素自訂屬性的操作(相容Firefox和IE)

來源:互聯網
上載者:User

 很多情況下,我們常常通過javascript對HTML元素的屬性進行操作,如擷取或設定以下html代碼塊中input元素的value;

1 <input
id="input_btn"
type="button"
value="kanqd.com"
/>

我們常常會寫以下的代碼:

1
2
var inputObj
= document.getElementById('input_btn');
alert(inputObj.value);

如我們所想的一樣,頁面上彈出kanqd.com.

問題: 在一些應用產景中,我們需要對html元素的添加一些自訂屬性以滿足應用,比如,對給以上input標記加一個info屬性,代碼如下:

1 <input
id="input_btn"
type="button"
value="kanqd.com"  info="this is a self defined attribute"
/>;

如果我們還是以同樣的代碼進行操作:

1
2
var inputObj
= document.getElementById('input_btn');
alert(inputObj.info);

執行後會發現,在IE中彈出”this is a self defined attribute” , 但在firefox中它就出錯了,原因是IE自動將自訂屬性解析到了DOM中,和標準屬性沒有任何區別,但FireFox對自訂屬性的使用,限制更高.

相容方法如下:
1、用元素attributes[]集合來訪問:

1
2
3
4
var inputObj
= document.getElementById('input_btn');
alert(inputObj.attributes['info'].nodeValue);
inputObj.attributes['info'].nodeValue
= 'this is a new info';
alert(inputObj.attributes['info'].nodeValue);

2、用getAttribute 和 setAttribute對其進行操作:

1
2
3
4
var inputObj
= document.getElementById('input_btn');
alert(inputObj.
getAttribute('info'));
inputObj.setAttribute('info','this is a new info');
alert(inputObj.
getAttribute('info'));

^_^:
注意:這裡所說的自訂屬性是特指在html頁面中定義的元素屬性,用javascript動態建立的屬性不會有這個問題。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.