Liny_@NotePad

沉迷ACG中

简单的JS抽奖范例

YOYO posted @ 2012年5月21日 15:12 in 【Web开发】客户端 with tags javascript dom , 3390 阅读

操作DOM和取随机数的简单应用,截图如下:

代码如下:

<html>
<head>
<title>抽选</title>
</head>
<body>
<h3>抽选对象</h3>
请输入要抽选的对象:<input type="button" onclick="javascript:add()" value="添加" />
<div id="usersDiv">
</div>
<input type="button" onclick="javascript: lottery();" value="抽选" />
<hr>
<h3>抽选结果</h3>
<span id="memo"></span><br/>
<span id="user_id"></span>
<script language="javascript">
var users = [];
var usersDiv = document.getElementById("usersDiv");

add();

function lottery() {
	for(i = users.length - 1; i >= 0; --i) {
		if (users[i].childNodes[0].value == '') {
			remove(users[i]);
		}
	};
	var num = users.length;
	if (num <= 0) {
		alert('请至少输入一位候选人!');
		return;
	}
	var randIndex = Math.ceil(Math.random() * num);
	document.getElementById("memo").innerText = "共有" + num + "位候选人。";
	document.getElementById("user_id").innerHTML = "中奖者是编号" + randIndex + "的<strong>" + users[randIndex-1].childNodes[0].value + "</strong>。";
}

function remove(node) {
	usersDiv.removeChild(node);
	var idx = 0;
	for (i = 0; i < users.length; ++i) {
		if (users[i] == node) {
			idx = i;
			break;
		}
	}
	for (i = idx; i < users.length - 1; ++i) {
		users[i] = users[i + 1];
	}
	users.pop();
}

function add() {
	var num = users.length;

	var subDiv = document.createElement("div");
	usersDiv.appendChild(subDiv);

	var txt =document.createElement("input");
	txt.type="text";
	txt.size="15";
	subDiv.appendChild(txt);

	if (users.length > 0) {
		var btn = document.createElement("input");
		btn.type="button";
		btn.value="×";
		btn.onclick=function() {
			remove(subDiv);
		}
		subDiv.appendChild(btn);
	}
	
	users.push(subDiv);
	txt.focus();
}
</script>
</body>
</html>
  • 无匹配
NCERT Gk Sample Pape 说:
2022年9月29日 19:22

Subject experts have provided the latest version of NCERT GK Sample Paper 2023 Class 10 that’s supports for all formats of exams such as SA1, SA2, FA1, FA2, FA3, FA4 and Assignments conducting under Term-1 & Term-2 of the course. Candidates download the practice question bank with important questions from where which questions have asked repeatedly in the past years old exams, NCERT Gk Sample Paper Class 10 How they indirectly ask the questions and so on by follow those NCERT STD-10 GK Model Papers 2023.Subject experts have provided the latest version of NCERT GK Sample Paper 2023 Class 10 that’s supports for all formats of exams such as SA1, SA2, FA1, FA2, FA3, FA4 and Assignments conducting under Term-1 & Term-2 of the course.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter