对于练习测试,我被要求找到一种方法,使一个按钮显示段落中的文本。每次按下时,文本都必须更改。
第一次按下按钮应该说“你按了按钮” 第二个“你再次按下它 第三次到第五次“你按下按钮(一个数字从3到5)次” 它应该说“停止!”,然后它应该说“停止!”
编辑编辑编辑
这是整个原始HTML,我不确定是否需要它,但也许html可能与您给我的不适合我的javascript代码有关。
HTML
<!DOCTYPE html>
<html>
<head>
<script src="q2.js" type="text/javascript"></script>
</head>
<body>
<button type="button" onclick="go()">ClickMe</button>
<p id="output">
</p>
</body>
</html>
的JavaScript
function go() {
var out = document.getElementById("output");
var x = "hi there";
out.innerHTML = x;
}
我该怎么做才能使这项工作?
答案 0 :(得分:2)
使用switch
语句来避免嵌套的if
语句...
var testCount = 0;
var out = document.getElementById("output");
function go(){
testCount++;
switch (testCount) {
case 1:
out.innerHTML = 'you pressed the button';
break;
case 2:
out.innerHTML = 'you pressed it again';
break;
case 3:
case 4:
case 5:
out.innerHTML = 'you pressed the button ' + testCount + ' times';
break;
default:
out.innerHTML = 'stop!!';
break;
}
}
答案 1 :(得分:0)
或者这个怎么样?
'use strict';
let count = 0;
// define this outside of function so it won't be defined over and over
let out = document.getElementById('output');
let message;
function go(e){
e.preventDefault();
count ++;
out.innerHTML = count > 1 ? count === 2 ? 'You pressed the button again!' : count > 1 && count < 6 ? `You pressed the button ${count} times!` : 'Stop!' : 'You pressed the button';
}
// It's best practice to stay away from inline JS, you could define your click handler in your script block
// For the following to work add id="btn1" to your button and remove the onclick handler
document.getElementById('btn1').addEventListener('click', go);
答案 2 :(得分:-2)
你可以这样做:
'use strict';
let count = 0;
// define this outside of function so it won't be defined over and over
let out = document.getElementById('output');
let message;
function go(e){
e.preventDefault();
count ++;
if(count === 1) message = 'You pressed the button!';
if(count === 2) message = 'You pressed the button again';
if(count > 1 && count < 6) message = `You pressed the button ${count} times!`;
if(count >= 6) message = 'Stop!';
out.innerHTML = message;
}
// It's best practice to stay away from inline JS, you could define your click handler in your script block
// For the following to work add id="btn1" to your button and remove the onclick handler
document.getElementById('btn1').addEventListener('click', go);