使用Javascript更改Nested Span类

Change Nested Span class using Javascript

本文关键字:Span Nested 更改 Javascript 使用      更新时间:2023-09-26

当使用Javascript将span类嵌套在按钮元素中时,我在更改span类时遇到问题。

我正试图让它看起来像这样http://www.bootply.com/128062#我已经验证了CSS的工作原理。

HTML

<button id="submitbutton" class="btn btn-primary btn-lg" type="submit" onclick="onclickFunction();">
    <span id ="submit_span" class=""></span> Submit</button>

JavaScript

function onclickFunction() {
    document.getElementById('submitbutton').className = 'btn btn-lg btn-warning';
    document.getElementById('submitbutton').innerHTML = 'Loading...';
    document.getElementById('submit_span').className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';
}

当您写入按钮的.innerHTML时,您正在销毁<span>元素。

相反,选择按钮的.lastChild,并更新其.data(假设文本位于此处)

function onclickFunction() {
    document.getElementById('submitbutton').className = 'btn btn-lg btn-warning';
    document.getElementById('submitbutton').lastChild.data = 'Loading...';
    document.getElementById('submit_span').className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';
}

如果您只是将this传递到函数中,那么您的代码会更短、更干净。

function onclickFunction(btn) {
  // The button element
  btn.className = 'btn btn-lg btn-warning';
  // The last text node in the button
  btn.lastChild.data = 'Loading...';
  // The first element (span) in the button
  btn.firstElementChild.className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';
}
.btn.btn-lg.btn-warning {
  background: orange
}
.glyphicon {
  padding: 10px;
  background: red;
  }
<button onclick="onclickFunction(this);" id="submitbutton" class="btn btn-primary btn-lg" type="submit">
  <span id="submit_span" class="">x</span> Submit
</button>

根据需要调整更新的图元。不确定你预期的东西会去哪里。

正确的顺序应该是:

function onclickFunction() {
    document.getElementById('submitbutton').className = 'btn btn-lg btn-warning';
    document.getElementById('submit_span').innerHTML = 'Loading...';
    document.getElementById('submit_span').className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';
}

斜视提供的答案并不遥远,但并不正确。我也不得不把它改成这个。上一个

// The first element (span) in the button
btn.firstChild.className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';

之后

btn.firstElementChild.className = 'glyphicon glyphicon-refresh glyphicon-refresh-animate';

我在chrome中找到了这一点,检查元素,检查DOM属性,展开控制台中的按钮,您将看到firstElementChild。