为了账号安全,请及时绑定邮箱和手机立即绑定

更改按钮的文本以动态包含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 关注
  • 249 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信