在處理動態生成或服務端渲染的HTML時,常需讀取元素上綁定的內聯事件代碼字符串(如onchange="test();")。本文對比getAttribute、getAttributeNode、jQuery.attr()三種方式的差異,給出穩健獲取方案。
<select id="city" onchange="javascript:test();"></select> // 需獲取字符串 "javascript:test();"
| 方法 | 返回值類型 | 事件屬性表現 | 兼容性 |
|---|---|---|---|
elem.getAttribute('onchange') | String / Function | 現代瀏覽器返回函數對象,非字符串 | 不穩定 |
elem.getAttributeNode('onchange').nodeValue | String | 始終返回原始HTML屬性字符串 | 全瀏覽器 |
$(elem).attr('onchange') | String / Function | jQuery內部處理不一,版本差異大 | 不推薦 |
var select = document.getElementById('city');
var attrNode = select.getAttributeNode('onchange');
var eventCode = attrNode ? attrNode.nodeValue : null;
// 返回 "javascript:test();" (原始字符串)
getAttribute:IDL屬性獲取器,對事件屬性返回編譯後的函數對象(標準行為)getAttributeNode:返回Attr節點對象,.nodeValue保留原始HTML屬性文本function getInlineEventHandler(element, eventName) {
// eventName: 'onclick', 'onchange', 'onload' 等
var attr = element.getAttributeNode(eventName);
return attr && attr.nodeValue;
}
// 用法
var code = getInlineEventHandler(document.getElementById('city'), 'onchange');
if (code) {
// 可用 new Function(code) 執行,或正則解析參數
console.log('事件代碼:', code);
}
// jQuery 1.x 可能返回字符串 // jQuery 3.x 返回函數對象 (模擬IDL行為) // 版本升級導致邏輯失效,極不推薦用於讀取內聯事件
<select data-handler="test"> + dataset.handler,關注點分離element.addEventListener('change', test),避免內聯事件@change、ReactonChange、Angular(change)唯有
getAttributeNode(name).nodeValue能穩定跨瀏覽器、跨庫版本獲取原始內聯事件字符串。新項目請棄用內聯事件,採用非侵入式綁定。