JS removeAttribute()方法實(shí)現(xiàn)刪除元素的某個(gè)屬性
在 JavaScript 中,使用元素的 removeAttribute() 方法可以刪除指定的屬性。用法如下:removeAttribute(name)
參數(shù) name 表示元素的屬性名。
示例1下面示例演示了如何動(dòng)態(tài)設(shè)置表格的邊框。
<script> window.onload = function () { //綁定頁(yè)面加載完畢時(shí)的事件處理函數(shù) var table = document.getElementByTagName('table')[0]; //獲取表格外框的引用 var del = document.getElementById('del'); var reset = document.getElementById('reset'); del.onclick = function () { table.removeAttribute('border'); } reset.onclick = function () { table.setAttribute('border', '2'); }</script><table border='2'> <tr> <td>數(shù)據(jù)表格</td> <tr></table><button id='del'>刪除</button><button id='reset'>恢復(fù)</button>
在上面示例中設(shè)計(jì)了兩個(gè)按鈕,并分別綁定了不同的事件處理函數(shù)。單擊“刪除”按鈕即可調(diào)用表格的 removeAttribute() 方法清除表格邊框,單擊“恢復(fù)”按鈕即可調(diào)用表格的 setAttribute() 方法重新設(shè)置表哥便可的粗細(xì)。
示例2下面示例演示了如何自定義刪除類函數(shù),并調(diào)用該函數(shù)刪除指定類名。
<script> function hasClass (element, className) { //類名檢測(cè)函數(shù) var reg = new RegExp (’(s|^)’ + className + ’(s|$)’); return reg.test (element, className); //使用正則檢測(cè)是否有相同的樣式 } function deleteClass (element, className) { if (hasClass (element, className)) { element.className.replace (reg, ’ ’); //捕獲要?jiǎng)h除樣式,然后替換為空白字符串 } }</script><div class='red blue bold'>盒子</div><script> var red = document.getElementById ('red'); deleteClass (red, ’blue’);</script>
上面代碼使用正則表達(dá)式檢測(cè) className 屬性值字符串中是否包含指定的類名,如果存在,則使用空字符串替換掉匹配到的子字符串,從而實(shí)現(xiàn)刪除類名的目的。
removeAttribute與removeAttributeNode方法異同removeAttribute
移除節(jié)點(diǎn)指定名稱的屬性。示例如下
document.getElementById(’riskTypePie’).removeAttribute('style');
removeAttributeNode注:此方法不兼容IE。
使用方法:
獲取要?jiǎng)h除屬性的元素 獲取該元素要?jiǎng)h除的屬性 <元素>.removeAttributeNode<屬性>var node=document.getElementById(’chartWrap’);var attr=n.getAttributeNode(’style’);node.removeAttributeNode(attr);
異同分析
相同點(diǎn)
兩個(gè)方法都是用來(lái)移除節(jié)點(diǎn)屬性 兩種方法調(diào)用者都只能是標(biāo)簽節(jié)點(diǎn)不同點(diǎn)
removeAttribute方法接收的是要?jiǎng)h除屬性的名字 removeAttributeNode方法接收的是要?jiǎng)h除的屬性節(jié)點(diǎn)它本身到此這篇關(guān)于JS removeAttribute()方法實(shí)現(xiàn)刪除元素的某個(gè)屬性的文章就介紹到這了,更多相關(guān)JS removeAttribute()刪除元素屬性內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼2. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼3. ASP常用日期格式化函數(shù) FormatDate()4. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)5. html中的form不提交(排除)某些input 原創(chuàng)6. CSS3中Transition屬性詳解以及示例分享7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. python 如何在 Matplotlib 中繪制垂直線9. jsp文件下載功能實(shí)現(xiàn)代碼10. 開發(fā)效率翻倍的Web API使用技巧
