当 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/