javascript - 使用 Javascript 更改嵌套跨度类

标签 javascript html css twitter-bootstrap

当 span 类嵌套在带有 Javascript 的按钮元素内时,我在更改 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';
}

最佳答案

你正在破坏 <span>当您写入 .innerHTML 时的元素的按钮。

相反,选择 .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>

根据需要调整更新的元素。不确定您希望东西去哪里。

关于javascript - 使用 Javascript 更改嵌套跨度类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37172304/

相关文章:

java - 如何在网页上显示动态生成的图像(条形码)?

html - Twitter Bootstrap - DIV 绝对位置到图像响应放大

html - Bootstrap : data-target collapsing several divs

javascript - 预填充受控组件

javascript - 是否可以将流类型包装在不可变容器中?

java - 从 Java websocket 服务器发送图像

html - 如何 Hook DOM 加载事件?

javascript - 只显示一个段落......不管是否有更多,空白,空白,类......只有并且只有CSS

javascript - 为什么 moment-timezone 不适用于给定的时区

javascript - 如何在 React 中删除包含子组件的功能性内存组件的渲染器?