dom对象是什么--乐字节大数据

DOM对象

DOM:Document Object Model 文档对象模型

要实现页面的动态交互效果,bom 操作远远不够,需要操作 html 才是核心。如何操作 htm,就是 DOM。简单的说,dom 提供了用程序动态控制 html 接口。DOM即文档对象模型描绘了一个层次化的节点树,运行开发人员添加、移除和修改页面的某一部分。dom 处于javascript 的核心地位上。

每个载入浏览器的 HTML 文档都会成为 Document 对象。Document 对象使我们可以从脚本中对 HTML 页面中的所有元素进行访问。Document 对象是 Window 对象的一部分,可通过 window.document 属性对其进行访问。

image

节点

加载 HTML 页面时,Web 浏览器生成一个树型结构,用来表示页面内部结构。DOM 将这种树型结构理解为由节点组成,组成一个节点树。对于页面中的元素,可以解析成以下几种类型的节点:

节点类型 HTML内容 例如
文档节点 文档本身 整个文档 document
元素节点 所有的HTML元素 <a>、<div>、<p>
属性节点 HTML元素内的属性 id、href、name、class
文本节点 元素内的文本 hello
注释节点 HTML中的注释

html --> 文档节点

div --> 元素节点

title --> 属性节点

测试 Div --> 文本节点

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n38" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><html>
 <head>
 <title>树!树!到处都是树!</title>
 </head>
 <body>
 <div title="属性节点">测试 Div</div>
 </body>
</html></pre>
image

操作元素的节点

当HTML文档在被解析为一颗DOM树以后,里面的每一个节点都可以看做是一个一个的对象,我们称为DOM对象,对于这些对象,我们可以进行各式各样的操作,查找到某一个或者一类节点对象,可以创建某种节点对象,可以在某个位置添加节点对象,甚至可以动态地删除节点对象,这些操作可以使我们的页面看起来有动态的效果,后期结合事件使用,就能让我们的页面在特定时机、特定的事件下执行特定的变换。

获取节点

在进行增、删、改的操作时,都需要指定到一个位置,或者找到一个目标,此时我们就可以通过Document对象提供的方法,查找、定位某个对象(也就是我们说的节点)。

注意:操作 dom 必须等节点初始化完毕后,才能执行。

处理方式两种:

(1)把 script 调用标签移到html末尾即可;

(2)使用onload事件来处理JS,等待html 加载完毕再加载 onload 事件里的 JS。

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n50" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">window.onload = function () { //预加载 html 后执行};</pre>

获取方式如下:

方法 描述
getElementById() 根据id获取dom对象,如果id重复,那么以第一个为准
getElementsByTagName() 根据标签名获取dom对象数组
getElementsByClassName() 根据样式名获取dom对象数组
getElementsByName() 根据name属性值获取dom对象数组,常用于多选获取值

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n68" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><body>
<p id="p1" class="para">这是一个段落<span>文本</span></p>
<p id="p1" class="para">这又是一个段落</p>
<input type="text" name="txt" />
<input type="checkbox" name="hobby" value="游泳" />游泳
<input type="checkbox" name="hobby" value="篮球" />篮球
<input type="checkbox" name="hobby" value="足球" />足球
<hr />
<a href="javascript:void(0)" onclick="testById()">按照id获取</a>
<a href="javascript:void(0)" onclick="testByName()">按照name获取</a>
<a href="javascript:void(0)" onclick="testByTagName()">按照标签名获取</a>
<a href="javascript:void(0);" onclick="testByClass();">按照class获取</a>
</body></pre>

说明:href="javascript:void(0)":伪协议,表示不执行跳转,而执行指定的点击事件。

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n70" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><script type="text/javascript">
// 按照id获取元素
function testById() {
// 返回单个对象
var p = document.getElementById("p1");
console.log(p);
// 表示获取元素开始标签和结束标签之间的html结构
console.log(p.innerHTML);
console.log(p.innerText); // 表示获取标签之间的普通文本
}

// 按照name获取元素
function testByName() {
// 对象数组
var ho = document.getElementsByName("hobby");
console.log(ho);
for(var i = 0; i <= ho.length - 1; i++) {
console.log(ho[i].value);
}
}

// 按照标签名获取元素
function testByTagName() {
// 对象数组
var inputArr = document.getElementsByTagName("input");
for(var i = 0; i < inputArr.length; i++) {
if(inputArr[i].type == "text") {
console.log("text类型");
} else if(inputArr[i].type == "checkbox") {
if(inputArr[i].checked) {
console.log(inputArr[i].value);
}
}
}
}

// 按照class属性获取元素
function testByClass() {
// 对象数组
var ps = document.getElementsByClassName("para");
console.log(ps[0].innerHTML);
ps[0].innerHTML += "这是一段新的文本";
}
</script></pre>

创建节点和插入节点

很多时候我们想要在某个位置插入一个新的节点,此时我们首先需要有一个节点存在,可以通过以下几种方式创建新节点。

创建节点
方法 描述
createElement() 创建一个新的节点,需要传入节点的标签名称,返回创建的元素对象
createTextNode() 创建一个文本节点,可以传入文本内容
innerHTML 也能达到创建节点的效果,直接添加到指定位置了
插入节点
方法 描述
write() 将任意的字符串插入到文档中
appendChild() 向元素中添加新的子节点,作为最后一个子节点
insertBefore() 向指定的已有的节点之前插入新的节点newItem:要插入的节点exsitingItem:参考节点 需要参考父节点

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n101" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><button onclick="add()">添加段落</button>
<div id="container"></div>

<script type="text/javascript">
function add(){
var container = document.getElementById('container')
var paragraph = document.createElement('p');
var txt = document.createTextNode('hello')
paragraph.appendChild(txt)
container.appendChild(paragraph)
}
</script></pre>

添加 "段落、图片、文本框、选项"

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n103" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><body>
<button onclick="addPara();">添加段落</button>
<button onclick="addImg();">添加图片</button>
<button onclick="addTxt();">添加文本框</button>
<button onclick="addOptions()">添加选项</button>
<select name="music">
<option value="-1">你心内的一首歌</option>
<option value="0">南山南</option>
<option value="1">喜欢你</option>
</select>
<hr />
<div id = "container"></div>
</body></pre>

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n104" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><script type="text/javascript">
// 添加p节点
function addPara(){
// 获取容器
var container =document.getElementById("container");
// 创建段落<p></p>
var p =document.createElement('p');
// 第一种方式
// 创建文本节点
var txt=document.createTextNode("以后的你会感谢现在努力的你");
// 将txt节点追加到p节点中
p.appendChild(txt);
// 将p节点追加到container节点中
container.appendChild(p);
/*
// 第二种方式
// 向p节点中添加内容
p.innerHTML = "以后的你会感谢现在努力的你";
// 将p节点追加到container节点中
container.appendChild(p);
/
/

// 第三种方式
// 将字符串类型的p标签内容添加到container中,不会添加多次
var str = "<p>以后的你会感谢现在努力的你</p>";
container.innerHTML = str;
*/
}

// 添加图片
function addImg(){
// 创建图片
var img = document.createElement("img") ;
/*
// 设置属性第一种方式
// 设置img标签的src属性
// img.src ="http://www.baidu.com/img/bd_logo1.png";
*/
// 设置属性第二种方式
// setAttribute() 方法添加指定的属性,并为其赋指定的值。
// 设置img的src属性
img.setAttribute('src','http://www.baidu.com/img/bd_logo1.png');
img.style.width = '300px';
img.style.height = '200px';
// 获取容器
var container =document.getElementById("container");
// 将img节点追加到container中。
container.appendChild(img);
}

// 添加文本框
function addTxt(){
// 创建文本框
var txt =document.createElement("input");
/*
// 设置类型第一种方式
txt.type = "text";
txt.value = "添加成功";
/
// 设置类型第二种方式
txt.setAttribute('type', 'text');
txt.setAttribute('value', '添加成功');
/

  • txt.type = 'password'
  • txt.value = '123'
    */
    // 获取容器
    var container =document.getElementById("container");
    // 将txt节点追加到container中。
    container.appendChild(txt);
    }

// 添加下拉框的选项
function addOptions(){
// 第一种方式
/*
// 创建下拉项
var option = document.createElement("option") ;
option.value = "2" ;
option.text = "油菜花" ;
// 获取下拉框
var sel = document.getElementsByTagName("select")[0];
// 添加 下拉项
sel.appendChild(option);
*/
// 第二种方式:
var option = document.createElement("option") ;
option.value = "2" ;
option.text = "不该" ;
// 获取下拉框
var sel = document.getElementsByTagName("select")[0];
// 添加下拉项
sel.options.add(option);
// 第三种方式: 添加下拉项
var sel = document.getElementsByTagName("select")[0];
sel.innerHTML += "<option value = '2'>英雄</option>" ;
}
</script></pre>

间接查找节点

| 方法|属性 | 描述 |
| --- | --- |
| childNodes | 返回元素的一个子节点的数组 |
| firstChild | 返回元素的第一个子节点 |
| lastChild | 返回元素的最后一个子节点 |
| nextSibling | 返回元素的下一个兄弟节点 |
| parentNode | 返回元素的父节点 |
| previousSibling | 返回元素的上一个兄弟节点 |

删除节点

| 方法|属性 | 描述 |
| --- | --- |
| removeChild() | 从元素中移除子节点 |

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n138" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><script type="text/javascript">
function delNode(){
var programmer =document.getElementById("programmer");
// 从父元素中删除节点,获取要删除对象的父元素,然后从父元素中删除该对象
programmer.parentNode.removeChild(programmer);
}
</script>
<body>
<span id="programmer">程序猿</span>
<a href="javascript:void(0)" onclick="delNode();">删除</a>
</body></pre>

表单

表单是我们页面向后台传输数据的一种非常常见的方式,在进行数据发送(请求发出)之前,我们应该现在页面进行一系列数据合法性的验证,节省不必要的错误数据的传输,以及提高用户的体验度。

获取表单

前两种常用

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n144" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">1、document.表单名称
2、document.getElementById(表单 id);
3、document.forms[表单名称]
4、document.forms[索引]; //从 0 开始</pre>

例如:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n146" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><body>
<form id='myform' name="myform" action="" method="post"></form>
<form id='myform2' name="myform2" action="" method="post"></form>
</body>
<script>
//四种方式
var form =document.getElementById("myform");
form =document.myform;
form =document.forms["myform"];
form =document.forms[0];
console.log(form);
</script></pre>

获取表单元素

获取input元素

如 text password hidden textarea等,前两种常用。

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n151" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">1)、通过 id 获取:document.getElementById(元素 id);
2)、通过 form.名称形式获取: myform.元素名称; name属性值
3)、通过 name 获取 :document.getElementsByName(name属性值)[索引] // 从0开始
4)、通过 tagName 数组 :document.getElementsByTagName('input')[索引] // 从0开始</pre>

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n152" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><body>
<form id='myform' name="myform" action="" method="get">
姓名:<input type="text" id="uname" name="uname" value="zs"/><br />
密码:<input type="password" id="upwd" name="upwd" value="1234"/><br />
<input type="hidden" id="uno" name="uno" value="隐藏域" />
个人说明:<textarea name="intro"></textarea>
<button type="button" onclick="getTxt();" >获取元素内容</button>
</form>
</body>
<script>
function getTxt(){
var uno = document.getElementById("uno");
var uname = myform.uname;
console.log(uname + "--------");
var upwd = document.getElementsByTagName('input')[1] ;
var intro = document.getElementsByName("intro")[0];
console.log(uno.value +","+ uname.value +","+ upwd.value +","+ intro.value);
}
</script></pre>

获取单选按钮

前提:将一组单选按钮设置相同的name属性值

(1)获取单选按钮组:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n157" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">document.getElementsByName("name属性值");</pre>

(2)遍历每个单选按钮,并查看单选按钮元素的checked属性

若属性值为true表示被选中,否则未被选中

选中状态设定: checked='checked' 或 checked='true' 或 checked

未选中状态设定: 没有checked属性 或 checked='false'

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n162" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><form action="" name="myform">
<input type="text" name="inputName" value="aaa" />
<input type="radio" name="rad" value="1" /> 1
<input type="radio" name="rad" value="2" /> 2
</form>

<script type="text/javascript">
var radios = document.getElementsByName('rad');
//radios[0].checked = 'checked'
for(var i = 0; i<radios.length; i++){
console.log(radios[i].checked + '---' + radios[i].value)
}
</script></pre>

获取多选按钮

操作方式与单选同理,不同之处在于可以多选

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n166" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var ufav = document.getElementsByName("ufav");
var favstr = "";
for (i = 0;i < ufav.length; i++){
if(ufav[i].checked){
favstr += ufav[i].value+",";
}
}
favstr = favstr.substr(0,favstr.length-1);</pre>

获取下拉选项

(1)获取 select 对象:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n170" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var ufrom = document.getElementById("ufrom");</pre>

(2)获取选中项的索引:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n172" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var idx = ufrom.selectedIndex;</pre>

(3)获取选中项 options 的 value属性值:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n174" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var val = ufrom.options[idx].value;</pre>

注意:当通过options获取选中项的value属性值时,

若没有value属性,则取option标签的内容

若存在value属性,则取value属性的值

(4)获取选中项 options 的 text:

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n179" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var txt = ufrom.options[idx].text;</pre>

选中状态设定:selected='selected'、selected=true、selected

未选中状态设定:不设selected属性

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n182" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><body onload="init()">
<form id='myform' name="myform" action="" method="">
来自:
<select id="ufrom" name="ufrom">
<option value="-1" >请选择</option>
<option value="0" selected="selected">北京</option>
<option value="1">上海</option>
</select><br />
<button type="button" id="sub" name="sub">提交</button>
</form>
</body>
<script>
function init () {
var sub = document.getElementById("sub");
sub.onclick = function () {
//获取select对象
var ufrom = document.getElementById("ufrom");
console.log("表单对象:" + ufrom);
//获取选中的索引
var idx = ufrom.selectedIndex;
console.log("选中项的索引值:" + idx);
//获取选中项的value值
var val = ufrom.options[idx].value;
console.log("选中项的value属性值:" + val);
//获取选中项的text
var txt = ufrom.options[idx].text;
console.log("选中项的text:" + txt);
}
}
</script></pre>

提交表单

(1)使用普通button按钮+onclick事件+事件中编写代码:

获取表单.submit();

(2)使用submit按钮 + onclick="return 函数()" +函数编写代码:

最后必须返回:return true|false;

(3)使用submit按钮/图片提交按钮 + 表单onsubmit="return 函数();" +函数编写代码:

最后必须返回:return true|false;

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n191" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><form id='myform1' name="myform2" action="#" method="get" onsubmit="return onsub();">
<input name="test" id="uname"/><span id="msg"></span><br />

<input type="button" onclick="sub();" value="提交表单1" />
<input type="submit" onclick="return sub2();" value="提交表单2" />
<input type="submit" value="提交onsubmit" /><br />
<input type="image" src="img/u=71331624,2965806045&fm=23&gp=0.jpg"
width="60px" height="40px" />
</form>
<script type="text/javascript">
// input的type=button,调用submit()方法提交
function sub(){
document.myform2.submit();
}
// 进行校验,返回值为true才能提交
function sub2(){
var uname = document.getElementById("uname");
var val = uname.value;
if(val.length>0){
return true; // 提交
}
document.getElementById("msg").innerHTML = "不能空着啊!!!";
document.getElementById("msg").style.color="red";
return false; // 不提交
}
// onsubmit事件提交
function onsub () {
var uname = document.getElementById("uname");
var val = uname.value;
if(val.length>0){
return true; // 提交
}
document.getElementById("msg").innerHTML = "填写点儿东西呗!(ˉ▽ ̄~) 切~~";
document.getElementById("msg").style.color="red";
return false; // 不提交
}
</script></pre>

表单校验

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="html" contenteditable="true" cid="n194" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><form id='myform' name="myform">
姓名:<input type="text" id="uname" name="uname" /><br />
密码:<input type="password" id="upwd" name="upwd" /><br />
年龄:<input type="radio" name="uage" value="0" checked="checked"/>小屁孩
<input type="radio" name="uage" value="1"/>你懂得 <br />
爱好:<input type="checkbox" name="ufav" value="篮球"/>篮球
<input type="checkbox" name="ufav" value="爬床"/>爬床
<input type="checkbox" name="ufav" value="代码"/>代码<br />
来自:<select id="ufrom" name="ufrom">
<option value="-1" selected="selected">请选择</option>
<option value="0">北京</option>
<option value="1">上海</option>
</select><br />
<div id="validate" style="color: red;"></div>
<button type="submit" onclick="return checkForm();">提交</button>
<button type="reset" onclick="resetForm();">重置</button>
</form></pre>

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n195" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">/**
要求:
1、验证用户名
1)不能为空
2)长度为 6-12 位
2、验证密码
1)不能为空 *
2)长度为 6-12 位
3)不能包含用户名
3、年龄: 必须选择 你懂得
4、爱好: 必须选择一项
5、来自: 必须选择一项
满足以上条件
1、弹出所有的内容
2、提交表单
否则
1、说明错误原因
2、不能提交表单
*/</pre>

<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" contenteditable="true" cid="n196" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 通过id属性值得到dom对象
function (id) { return document.getElementById(id); } // 重置表单所有元素 注意函数不能命名为 clear reset 等 function resetForm(){ // 获取说明 div var validate =('validate');
validate.innerHTML ="";
}
// 表单校验
function checkForm () {
var flag =true;
// 获取说明 div
var validate = ('validate'); validate.innerHTML =""; // 1、验证用户名 // 1)、获取用户名的值 var uname =('uname').value;
// 1)不能为空 -->后期正则处理
// 2)长度为 6-12 位
if("" === uname || uname.length == 0 ){
validate.innerHTML += "用户名不能为空</br>";
flag = false;
}else if(uname.length < 6 || uname.length > 12){
validate.innerHTML += "
用户名长度在 6-12 位</br>";
flag = false;
}
// 2、验证密码
var upwd = ('upwd').value; // 1)不能为空 // 2)长度为 6-12 位 // 3)不能包含用户名 if("" === upwd || upwd.length == 0 ){ validate.innerHTML += "*密码不能为空</br>"; flag = false; } else if(upwd.length < 6 ||upwd.length > 12){ validate.innerHTML += "*密码长度在 6-12 位</br>"; flag = false; } else if(uname.length > 0 && upwd.indexOf(uname) >= 0){ validate.innerHTML += "*密码中不能出现用户名</br>"; flag = false; } // 3、年龄: 必须选择 你懂得 var ageGroup = document.getElementsByName("uage"); var age ; for (var i = 0; i < ageGroup.length; i++) { if(ageGroup[i].checked){ age = ageGroup[i].value; } } if(age == 0){ flag = false; validate.innerHTML += "*小屁孩,妈妈喊你回家</br>"; } // 4、爱好: 必须选择一项 var ufav = document.getElementsByName("ufav"); var favstr = ""; for (i = 0;i < ufav.length; i++){ if(ufav[i].checked){ favstr += ufav[i].value + ","; } } favstr = favstr.substr(0,favstr.length-1); if(favstr.length < 1){ flag = false; validate.innerHTML += "*人生真无趣</br>"; } // 5、来自 var ufrom =('ufrom');
var idx = ufrom.selectedIndex ;
var val = ufrom.options[idx].value;
var valTxt = ufrom.options[idx].text;
if(-1 == val){
flag = false;
validate.innerHTML += "*你来自火星吗?</br>";
}
// 满足以上条件 弹出内容
if(flag){
var str = "";
str += "您的姓名是:" + uname + "\n";
str += "您的密码是:" + upwd + "\n";
str += "您的年龄是:" + "可以赢取白富美了" + "\n";
str += "您的爱好是:" + favstr + "\n";
str += "您来自于:" + valTxt + "\n";
alert(str);
// 设置表单提交的地址
myform.action="http://www.baidu.com";
// 提交表单
myform.submit();
return false;
} else {
return false;
}</pre>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355