我希望这个java脚本显示按钮下面没有按钮的答案,请看看

时间:2015-10-15 03:23:50

标签: javascript dom

所以基本上这段代码使文本按下按钮但我希望它显示在按钮下方,所以每次我点击按钮时文本都会更新如下:https://jsfiddle.net/santon/mc15vy4f/< -----示例

  var myBtn = document.getElementById("myButton");

 var clickTracker = {
      count:0,
    getMessage: function() {
    var message;

    switch(this.count) {
        case 1: message = "You pushed the button"; break;
        case 2: message = "You pushed the button (again)."; break;
        case 3: //fall Through
        case 4: //fall Through
        case 5: //fall Through
            message = "You pushed the button "+ this.count + " times."; break;
        default: message = "Stop pushing the button"    
    }
    return message;
   }
};


 function processClick() {
    clickTracker.count++;
       this.innerHTML = clickTracker.getMessage();
 }

 myBtn.addEventListener("click", processClick);

2 个答案:

答案 0 :(得分:0)

在这一行:

this.innerHTML = clickTracker.getMessage();

你告诉按钮改变它的内部HTML。 如果要在按钮后面显示text / html,可以执行以下操作:

 var myBtn = document.getElementById("myButton");
var textContainer;

 var clickTracker = {
      count:0,
    getMessage: function() {
    var message;

    switch(this.count) {
        case 1: message = "You pushed the button"; break;
        case 2: message = "You pushed the button (again)."; break;
        case 3: //fall Through
        case 4: //fall Through
        case 5: //fall Through
            message = "You pushed the button "+ this.count + " times."; break;
        default: message = "Stop pushing the button"    
    }
    return message;
   }
};


 function processClick() {
    clickTracker.count++;
       var text = clickTracker.getMessage();
       if(!textContainer){ //checking if container is not yet set
           textContainer = document.createElement("div"); //creating the element
           this.parentElement.appendChild(textContainer);//appending to parent of button
       }
       textContainer.textContent = text;
 }

 myBtn.addEventListener("click", processClick);

答案 1 :(得分:0)

像这样更改你的HTML:

<button id="myButton">Click Me</button>
<p id="stat"></p>

这样的JS代码:

var myBtn = document.getElementById("myButton");

var clickTracker = {
    count:0,
    getMessage: function() {
        var message;

        switch(this.count) {
            case 1: message = "You pushed the button"; break;
            case 2: message = "You pushed the button (again)."; break;
            case 3: //fall Through
            case 4: //fall Through
            case 5: //fall Through
                message = "You pushed the button "+ this.count + " times."; break;
            default: message = "Stop pushing the button"    
        }
        return message;
    }
};


function processClick() {
    clickTracker.count++;
    document.getElementById("stat").innerHTML = clickTracker.getMessage();
}

myBtn.addEventListener("click", processClick);