How to toggle the innerHTML of element on click

你说的曾经没有我的故事 提交于 2019-12-08 12:13:31

问题


How do I toggle an element's innerHTML on click with pure JS?

(function(){
    var div = document.getElementById("hook");

    div.addEventListener("click", function(){
        div.innerHTML = "I've been clicked";
    }, false);
})();

http://jsfiddle.net/Z2UBs/1/


回答1:


Simplest way (to show you the idea behind this):

    (function(){
        var div = document.getElementById("hook");

        div.addEventListener("click", function(){

            var state1 = document.getElementById('t1').value;
            var state2 = document.getElementById('t2').value;

            if ( div.innerHTML == state1 ) {
                div.innerHTML = state2;
            }
            else if ( div.innerHTML == state2 ) {
                div.innerHTML = state1;
            }
            // add as many dynamic values as you wish here
            else {
                // to be on the safe side
                div.innerHTML = state1;
            }
        }, false);

    })();

FIDDLE

If you want it to be more efficient then introduce boolean variables for representing the current state.




回答2:


Try this

(function(){
            var div = document.getElementById("hook");
            var curText = div.innerText;
            div.addEventListener("click", function(){
            if(this.innerText == curText){
                 div.innerText = "I've been clicked";
            }
            else{
                    div.innerText = curText;
            }
            }, false);

        })();

Here is jsfiddle



来源:https://stackoverflow.com/questions/20499920/how-to-toggle-the-innerhtml-of-element-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!