การคัดลอกรหัสมีดังนี้:
<! doctype html public "-// w3c // dtd xhtml 1.0 transitional // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" />
<title> ใช้ DOM เพื่อสร้างกล่องรายการแบบดรอปดาวน์ </title>
</head>
<body onload = "setFun ()">
<form>
<เลือกชื่อ = "พื้นที่" id = "พื้นที่">
<ตัวเลือกค่า = "0"> ไม่มีภูมิภาค </portion>
</เลือก>
</form>
<ภาษาสคริปต์ = "JavaScript">
ฟังก์ชั่น setFun () {
var id = อาร์เรย์ใหม่ (1,2,3);
var value = new Array ("Guizhou", "Chongqing", "Sichuan");
var select = document.getElementById ("พื้นที่");
select.length = 1; // ตั้งค่าเพียงตัวเลือกเดียวเท่านั้น
select.options [0]. selected = true; // ตั้งค่าตัวแรกถูกเลือกโดยค่าเริ่มต้น
สำหรับ (var x = 0; x <id.length; x ++) {
ตัวเลือก var = document.createElement ("ตัวเลือก");
ตัวเลือก. setAttribute ("value", id [x]); // ตั้งค่าแอตทริบิวต์ตัวเลือก
ตัวเลือก. AppendChild (document.createTextNode (value [x]));
เลือก AppendChild (ตัวเลือก); // เพิ่มตัวเลือกเพื่อเลือก
-
-
</script>
</body>
</html>