摘要:<!DOCTYPE html> <html> <head> <title>jq点击按钮,颜色随机改变,数字全部加一;</title> <script type="text/javascript" src="jquery-3.3.1.min.js"><
<!DOCTYPE html>
<html>
<head>
<title>jq点击按钮,颜色随机改变,数字全部加一;</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<style type="text/css">
p{
width: 40px;height: 40px;
border: 1px solid #ccc;
border-radius: 50%;
line-height: 40px;
text-align: center;
float: left;
margin-left: 10px;
}
.clear{clear: both;}
</style>
</head>
<body>
<div>
<p num="1">1</p>
<p num="2">2</p>
<p num="3">3</p>
<p num="4">4</p>
</div>
<div class="clear"></div>
<button>按钮</button>
<script type="text/javascript">
//改变每个p标签的颜色
function color(){
// 首先遍历p标签;
var p=document.getElementsByTagName('p');
for (var i = 0; i<p.length; i++) {
// 产生一个随机小数,乘以1000000,然后在四舍五入,拼接;
var a=Math.random()*1000000;
var b=Math.round(a);
var c='#'+b;
//输出每一个p标签的颜色;也就是输出了4次;
document.getElementsByTagName('p')[i].style.backgroundColor=c
}
}
//随机数字;
function num(){
var p=document.getElementsByTagName('p');
for (var i = 0; i<p.length; i++) {
// 产生一个随机小数,,然后在四舍五入,拼接;
var a=Math.random()*9;
var b=Math.round(a);
// document.write(b)
document.getElementsByTagName('p')[i].innerHTML=b;
}
}
//各个数字加一
function addone(){
var p=document.getElementsByTagName('p');
for (var i = 0; i<p.length; i++) {
var n=parseInt(document.getElementsByTagName('p')[i].innerHTML)+1;
// document.write(n)
document.getElementsByTagName('p')[i].innerHTML=n;
}
}
//点击按钮,产生随机数字和颜色;
$(document).ready(function(){
$('button').click(function(){
//随机改变颜色
$(this).css('background',color())
//随机改变数字
$(this).text(num())
//每次都只加一
$(this).html(addone())
})
})
</script>
</body>
</html>![1554802986701767.png B@0]LUC]6U3U_%BT}W)B6UD.png](http://img.php.cn/upload/image/590/260/556/1554802986701767.png)
批改老师:天蓬老师批改时间:2019-04-10 10:32:47
老师总结:获取一些随机数, 在编程中是非常有用的功能, 例如要求你写一个抽奖的程序, 其实也是一些随机数