这三类表单在前端表单操作里面相对复杂一点,特总结此篇,便于今后的开发,也希望对你有所帮助。

一、select表单

** JS操作 **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//动态获取值
var Selt = document.getElementById("selectBox");

if(Selt.addEventListener){
Selt.addEventListener("change",callbackFn);
}else{
Selt.attachEvent("change",callbackFn);
}

function callbackFn(event){
var e = event || window.event;
var _target = e.target;
var val = _target.value;
console.log(val);
}

上面获取值是通过事件对象获取,当然还可以直接通过select的索引值获取。

1
2
3
4
5
6
//直接获取值
var Selt = document.getElementById("selectBox");
var Index = Selt.selectedIndex;
var val = Selt[Index].value;
console.log(val);
}

** JQ操作 **
//动态获取值

1
2
3
4
5
6
7
8
9
10
11
12
13
$("#selectBox").on("change",function(){
$("#selectBox").each(function(i,e){
if($(this).prop("selected")){
console.log($(this).val());
}
});
});


//直接获取值
var val = $("#selectBox option:selected").val();
console.log(val);
}

二、radio表单(一组radio其name属性是相同的)

** JS操作 **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//动态获取值
var radios = document.getElementsByName("myradio");
for(var i = 0;i < radios.length; i++){
if(radios[i].addEventListener){
radios[i].addEventListener("change",callbackFn);
}else{
radios[i].attachEvent("change",callbackFn);
}
}
function callbackFn(event){
var e = event || window.event;
var _target = e.target;
if(_target.checked){
var val = _target.value;
console.log(val);
}
}


//直接获取
for(var i = 0; i < radios.length; i++){
if(radios[i].ckecked){
console.log(radios[i].value);
}
}

** JQ操作 **
//动态获取值

1
2
3
4
5
6
7
8
9
10
11
$("input[type=radio]").change(function(){
if($(this).prop("checked")){
console.log($(this).val());
}
});


//直接获取值
var val = $("input[type=radio]:checked").val();
console.log(val);
}

三、checkbox表单

** JS操作 **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//动态获取值
var radios = document.getElementsByName("myradio");
for(var i = 0;i < radios.length; i++){
if(radios[i].addEventListener){
radios[i].addEventListener("change",callbackFn);
}else{
radios[i].attachEvent("change",callbackFn);
}
}
function callbackFn(event){
var e = event || window.event;
var _target = e.target;
if(_target.checked){
var val = _target.value;
console.log(val);
}
}


//直接获取
for(var i = 0; i < radios.length; i++){
if(radios[i].ckecked){
console.log(radios[i].value);
}
}

** JQ操作 **
//动态获取值

1
2
3
4
5
6
7
8
9
10
11
$("input[type=checkbox]").change(function(){
if($(this).prop("checked")){
console.log($(this).val());
}
});


//直接获取值
var val = $("input[name=mycheckbox]:checked").val();
console.log(val);
}

四、全选反选

** JS操作 **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var checkAll = document.getElementById("checkAll");

if(checkAll.addEventListener){
checkAll.addEventListener("click",callbackFn);
}else{
checkAll.attachEvent("click",callbackFn);
}

function callbackFn(event){
var e = event || window.event;
var _target = e.target;

var checkboxs = document.getElementsByName("mycheckbox");
if(_target.checked){
for(var i = 0;i < checkboxs.length; i++){
checkboxs[i].checked = true;
}
}else{
for(var i = 0;i < checkboxs.length; i++){
checkboxs[i].checked = false;
}
}
}

//还可以对checkbox直接赋值,减少一次for循环
function callbackFn(event){
var e = event || window.event;
var _target = e.target;

var checkboxs = document.getElementsByName("mycheckbox");
checkboxs.checked = _target.checked;
}

** JQ操作 **

1
2
3
4
5
6
7
8
$(document).on('click', '#checkAll', function () {
var op = $(this).is(':checked');
if (op == true) {
$('[type=checkbox]').prop('checked', true);
} else {
$('[type=checkbox]').prop('checked', false);
}
});

五、JQ方法attr()prop()的区别

** 1.官方文档描述 **

attr(): Description: Get the value of an attribute for the first element in the set of matched elements.
获取并且设置匹配元素的attribute属性值

prop(): Description: Get the value of a property for the first element in the set of matched elements.
获取并且设置匹配元素的property属性值

一词之差,attributeproperty

** 2.attribute和property **

官方文档prop()下是这样写的:
Attributes vs. Properties
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

考虑到在Jquery1.6之前attr()方法检索属性值返回结果有些不一致,在1.6+后,提供prop()方法明确的检索属性值当用attr()检索时,这在jquery源码中可以看到。

在编写HTML代码时,你可以在HTML元素中定义attribute属性。然而,当浏览器渲染解析页面时,该HTML元素相应的DOM节点就会被创建。该节点是一个对象,因此它就拥有properties。 因此,我们知道attributes是HTML元素(标签)的属性,而properties是DOM对象的属性。

举个例子:
<input id="myinput" type="text" value="Name">

其对应DOM节点会拥有如下properties: id、type 和 value:

  • idproperty是idattribute的映射:获取该property即等于读取其对应的attribute值,而设置该property即为attribute赋值。id是一个纯粹的映射property,它不会修改或限制其值。

  • typeproperty是typeattribute的映射:获取该property即等于读取其对应的attribute值,而设置该property即为attribute赋值。但type并不是一个纯粹的映射property,因为它的值被限制在已知值(即input的合法类型,如:text、password)。如果你有 ,然后 theInput.getAttribute(“type”) 会返回 “foo”,而 theInput.type 会返回 “text”。

  • 相比之下,valueproperty并不会映射valueattribute。取而代之的是input的当前值。当用户手动更改输入框的值,valueproperty会反映该改变。所以,如果用户在input输入John,然后:

theInput.value 返回 “John” 然而: theInput.getAttribute('value') 返回 “Name”。

valueproperty反映了input的当前文本内容,而valueattribute则是在 HTML源码 value 属性所指定的初始文本内容。

总结一下:attribute是HTML元素的属性,静态页面定义好的,propertype是js对象的属性值,可以是静态页面定义好的,也可以的动态操作的;attributeproperty是一对多的关系,简言之,attribute的值一定是property的值,反过来就不一定;通过官方文档建议,具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr()。

最后附上Jquery3.3.1源码,重点地方有注释,也可以看出在attr()方法里面调用prop()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},

removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );

jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value ); //清空property的name值
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ]; //返回property的name值
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
if ( tabindex ) {
return parseInt( tabindex, 10 );
}
if (
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) &&
elem.href
) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name ); //移除name属性
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" ); //设置attribute
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value ); //设置attribute
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match( rnothtmlwhite );

if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );

注:参考文章