1. 程式人生 > >【前端筆記】使用jquery實現簡單的投票功能

【前端筆記】使用jquery實現簡單的投票功能

首先先明確下需求:

  • 可以顯示是第幾輪投票
  • 顯示每輪共有幾票,還剩幾票
  • 如果這輪剩餘票數為0,留下票數最多的一個(如果有多個票數最高者,則都保留下來,進行下一輪投票,直至最後只有一位留下)

效果圖如下:

再次感嘆jquery比js原生程式碼簡短太多;

程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="../../../jquery/node_modules/jquery/dist/jquery.js"></script>
	<style>
		*{
			padding: 0px;
			margin-left: 0px;
		}
		ul>li{
			background: blue;
			width: 250px;
			height: 50px;
			border-radius: 0px 25px 25px 0px;
			margin-bottom: 10px;
		}
		ul >li >span,div{
			display: inline-block;
			height: 44px;
			width: 60px;
			text-align: center;
			line-height: 44px;
			color: #fff;
			font-weight: bold;
		}
		div{
			background: #000;
			margin-top: 2px;
			border-radius: 10px;
		}
		p,span{
			font-weight: bold;
		}
	</style>
</head>
<body>
<p>第<span>1</span>輪投票</p>
<ul>
	<li>
		<span class="num">0</span>
		<div>投票</div>
		<span>候選人1</span>
	</li>
	<li>
		<span class="num">0</span>
		<div>投票</div>
		<span>候選人2</span>
	</li>
	<li>
		<span class="num">0</span>
		<div>投票</div>
		<span>候選人3</span>
	</li>
	<li>
		<span class="num">0</span>
		<div>投票</div>
		<span>候選人4</span>
	</li>
</ul>
<p>剩餘<span>7</span>張</p>
<script>
	//投票點選事件
	$('div').click(function(){
		if ($('p:eq(1)').children().text()<=0) { return false}//判斷剩餘票數,如果是0,就不能再點選
		$(this).prev().text(function(index,text){return parseInt(text)+1})//給這個候選者的票數+1
		$('p:eq(1)').children().text(function(index,text){return parseInt(text)-1})//剩餘票數-1
		$(this).parent().animate({width:"+=50"},500)//用動畫來改變被投票者的長度
		var arr=[];
		var max=0;	
		$('.num').each(function(index){
			arr[index]=$(this).text()   //把每個投票者的票數存入陣列
		})
		$.each(arr,function(index,value){
			if (index==0) {
				max=arr[0] 
			}else{
				max=max>parseInt(arr[index])?max:parseInt(arr[index])   //取陣列最大值
			}
		})
		// console.log(arr)
		// console.log(max)
		//判斷剩餘票數是否為0,判斷元素隱藏 和 是不是要進入下一輪
		if ($('p:eq(1)').children().text()==0) {
			$('.num').each(function(){
				if ($(this).text()!=max) {
					$(this).parent().hide()          
				}
			})
			//新一輪
			if ($('li:visible').length>1) {
				$('p:eq(0)').children().text(function(index,text){return parseInt(text)+1})
				$('p:eq(1)').children().text(7)
			}
		}
	})