简体   繁体   中英

Bootstrap data-toggle=“button” not working with <span>

I'm using the 'data-toggle'-option from Bootstrap for a button. In the button I have a with glypicons and sometext. However, when you click on the text it works, but when you click on the glyphicon it doesn't trigger the data-toggle. Since the data-toggle does not work in JSFiddle I cannot post a link to it.

HTML:

<button type="button" id="showHide" class="btn btn-default" data-toggle="button"><span class="glyphicon glyphicon-eye-open"></span> show</button>

JavaScript:

document.getElementById("showHide").onclick = function () {
    if ($("#showHide").text() == " show") {
        document.getElementById("showHide").innerHTML = "<span class=\"glyphicon glyphicon-eye-close\"></span> hide";
        document.getElementById("showHide").blur();
    } else {
        document.getElementById("showHide").innerHTML = "<span class=\"glyphicon glyphicon-eye-open\"></span> show";
        document.getElementById("showHide").blur();
    }
}

I've looked online but haven't found a solution or someone with the same problem.

It appears the span is being replaced before the toggle event is propogated. You can use the button method to activate the toggle rather than the data attribute.

<button type="button" id="showHide" class="btn btn-default"><span class="glyphicon glyphicon-eye-open"></span> show</button>

document.getElementById("showHide").onclick = function () {
    if ($("#showHide").text() == " show") {
        document.getElementById("showHide").innerHTML = "<span class=\"glyphicon glyphicon-eye-close\"></span> hide";
        jQuery("#showHide").button('toggle');        
        document.getElementById("showHide").blur();
    } else {
        document.getElementById("showHide").innerHTML = "<span class=\"glyphicon glyphicon-eye-open\"></span> show";
        jQuery("#showHide").button('toggle');        
        document.getElementById("showHide").blur();
    }
}

View Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM