更改按钮的文本以动态包含span类

我遇到一个问题,我有一个按钮,在该按钮中我可以基于单击来更改其文本。

这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";         

}


慕容708150
浏览 250回答 3
3回答

开心每一天1111

textNode在i标记之后获取并更新其内容。function pingall(){&nbsp; // get the i tag within button then get the text content&nbsp; // after the tag using nextSibling property&nbsp; var textNode = document.querySelector('#btnShow i').nextSibling;&nbsp; // check textContetnt property for updating or checking&nbsp; if ((textNode.textContent).trim() == "Show All") {&nbsp; &nbsp; textNode.textContent = "Hide All";&nbsp; } else {&nbsp; &nbsp; textNode.textContent = "Show All";&nbsp; }}<button id='btnShow' class='btn btn-info pull-right' onclick='pingall()'><i class='fa fa-desktop'></i>Show All</button>

九州编程

发生这种情况是因为您在按钮内有一个图标元素。您可以将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>&nbsp;而JS可以:var showallButtonText=document.getElementById('btn-text');if((showallButtonText.innerText).trim()=="Show All"){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; showallButtonText.innerHTML="Hide All";}else{&nbsp; &nbsp; showallButtonText.innerHTML="Show All";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}

慕斯王

INNERHTML替换HTML元素内的所有内容。因此,在您的情况下,它将删除包括<span>标签在内的所有内容,并添加“全部隐藏”或“全部显示”。只需更换文本,你可以使用ID你的<span>元素。var textNode = document.querySelector('#idofyourspan');您也可以将后获得下一个元素<i>与nextSiblingvar 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 checkingif ((textNode.textContent).trim() == "Show All") {&nbsp; textNode.textContent = "Hide All";} else {&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript