如何在点击时切换元素的innerHTML

时间:2013-12-10 16:31:36

标签: javascript html innerhtml onclicklistener

如何使用纯JS切换元素的innerHTML?

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

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

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

2 个答案:

答案 0 :(得分:2)

最简单的方法(向您展示这背后的想法):

    (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

如果您希望它更有效,那么引入布尔变量来表示当前状态。

答案 1 :(得分:2)

试试这个

(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);

        })();

这是jsfiddle