亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更改按鈕的文本以動態包含span類

更改按鈕的文本以動態包含span類

慕容708150 2021-04-09 13:15:32
我遇到一個問題,我有一個按鈕,在該按鈕中我可以基于單擊來更改其文本。這button有一個span附件。但是,當我改變的價值innerHTML/innerText的button,將span被刪除,圖片多數民眾贊成應該來與button不出現。我嘗試添加"className"和'classList.add("text")',但是它只是拋出一個錯誤。所以我想知道是否有什么辦法只能更改the的文本而button不會影響該button's span元素。先感謝您 :)這是聲明按鈕的方式<button id='btnShow' class='btn btn-info pull-right' onclick='pingall()'><i class='fa fa-desktop'></i>Show All</button> 我正在使用javascript并通過更改文本的值var showallButton=document.getElementById('btnShow');if((showallButton.innerText).trim()=="Show All"){            showallButton.innerHTML="Hide All";}else{    showallButton.innerHTML="Show All";         }
查看完整描述

3 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

textNode在i標記之后獲取并更新其內容。


function pingall(){

  // get the i tag within button then get the text content

  // after the tag using nextSibling property

  var textNode = document.querySelector('#btnShow i').nextSibling;


  // check textContetnt property for updating or checking

  if ((textNode.textContent).trim() == "Show All") {

    textNode.textContent = "Hide All";

  } else {

    textNode.textContent = "Show All";

  }

}

<button id='btnShow' class='btn btn-info pull-right' onclick='pingall()'><i class='fa fa-desktop'></i>Show All</button>


查看完整回答
反對 回復 2021-04-22
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

發生這種情況是因為您在按鈕內有一個圖標元素。


您可以將HTML更新為:


<button id='btnShow' class='btn btn-info pull-right' onclick='pingall()'><i class='fa fa-desktop'></i><span id="btn-text">Show All</span></button> 

而JS可以:


var showallButtonText=document.getElementById('btn-text');

if((showallButtonText.innerText).trim()=="Show All"){        

    showallButtonText.innerHTML="Hide All";

}else{

    showallButtonText.innerHTML="Show All";         

}


查看完整回答
反對 回復 2021-04-22
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

INNERHTML替換HTML元素內的所有內容。

因此,在您的情況下,它將刪除包括<span>標簽在內的所有內容,并添加“全部隱藏”或“全部顯示”。

只需更換文本,你可以使用ID你的<span>元素。


var textNode = document.querySelector('#idofyourspan');

您也可以將后獲得下一個元素<i>與nextSibling


var textNode = document.querySelector('#btnShow i').nextSibling; // this should be your <span>

完整代碼:


var textNode = document.querySelector('#btnShow i').nextSibling; // get the next sibling after <i> tag inside button


// check textContetnt property for updating or checking

if ((textNode.textContent).trim() == "Show All") {

  textNode.textContent = "Hide All";

} else {

  textNode.textConten = "Show All";

}

function pingall(){

// your code


}

<button id='btnShow' class='btn btn-info pull-right' onclick='pingall()'><i class='fa fa-desktop'></i>Show All</button>


查看完整回答
反對 回復 2021-04-22
  • 3 回答
  • 0 關注
  • 271 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號