JavaScript的进一步学习
五个小练习
1.点击按钮出现弹窗
<body>
<p>点一下下面的按钮!</p>
<button onclick="myFunction('我的世界','小公主')">点击这里</button>
<script>
function myFunction(myworld,girl){
alert("欢迎来到" + myworld + ", 我娇贵的" + girl);
}
</script>
</body>
运行结果:
2.判断是否为两位数
<body>
<h1>JavaScript 验证输入</h1>
<p>请输入一个两位数</p>
<input id="numb">
<button type="button" onclick="myFunction()">提交</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
x = document.getElementById("numb").value;
if (isNaN(x) || x < 9 || x > 100) {
text = "输入错误";
} else {
text = "输入正确";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
运行结果:
3.文本输出
<body>
<input id="aaa">
<button type="button" onclick="myFunction()">提交</button>
<p id="demo"></p>
<script>
function myFunction() {
var text;
text = document.getElementById("aaa").value;
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
运行结果:
4.隐藏元素
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>隐藏元素</title>
<style>
#myBtn {
width: 300px;
height: 150px;
background-color: lightpink;
color: coral;
font-size: 35px;
}
.a {
display: none;
}
</style>
</head>
<body>
<button id="myBtn">点我有惊喜哦!</button>
<script>
var btn = document.getElementById("myBtn")
btn.addEventListener('click', function (event) {
document.getElementById("myBtn").classList.add("a");
})
</script>
</body>
点击前:
点击后:
5.计数器
<p><b>计数器</b></p>
<button type="button" onclick="myFunction()">计数!</button>
<p id="demo">0</p>
<script>
var counter = 0;
function add() {
return counter += 1;
}
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
点击前:
点击五次按钮后: