jQuery attr vs道具?

现在,这不仅仅是另一个问题了。我做了一些测试(http://jsfiddle.net/ZC3Lf/),修改了prop和attr,<form action="/test/"></form> 输出为:


1)道具修改测试

道具:http://fiddle.jshell.net/test/1

属性:http://fiddle.jshell.net/test/1


2)属性修改测试

属性:http://fiddle.jshell.net/test/1

属性:/test/1


3)属性然后进行道具修改测试

属性:http://fiddle.jshell.net/test/11

属性:http://fiddle.jshell.net/test/11


4)属性然后进行属性修改测试

属性:http://fiddle.jshell.net/test/11

属性:http://fiddle.jshell.net/test/11


现在,就我所知,我对两件事感到困惑:

道具:通过JavaScript进行任何修改后的当前状态

值:网页加载时html中定义的值。


现在,如果这是正确的,


为什么修改prop似乎使action完全合格,反之为什么不修改属性?

为什么修改propin 1)修改属性,那对我没有意义?

为什么修改attrin会2)修改属性,它们是要以这种方式链接?

测试代码

的HTML

的JavaScript


var element = $('form');

var property = 'action';


/*You should not need to modify below this line */


var body = $('body');

var original = element.attr(property);


body.append('<h1>Prop Modification test</h1>');

element.prop(property, element.prop(property) + 1);


body.append('Prop: '+element.prop(property)+'<br />');

body.append('Attr: '+element.attr(property)+'<hr />');


//reset

element.prop(property, original);

element.attr(property, original);


body.append('<h1>Attr Modification test</h1>');

element.attr(property, element.attr(property) + 1);


body.append('Prop: '+element.prop(property)+'<br />');

body.append('Attr: '+element.attr(property)+'<hr />');


//reset

element.prop(property, original);

element.attr(property, original);


body.append('<h1>Attr then Prop Modification test</h1>');

element.attr(property, element.attr(property) + 1);

element.prop(property, element.prop(property) + 1);


body.append('Prop: '+element.prop(property)+'<br />');

body.append('Attr: '+element.attr(property)+'<hr />');


//reset

element.prop(property, original);

element.attr(property, original);


body.append('<h1>Prop then Attr Modification test</h1>');

element.prop(property, element.prop(property) + 1);

element.attr(property, element.attr(property) + 1);


body.append('Prop: '+element.prop(property)+'<br />');

body.append('Attr: '+element.attr(property)+'<hr />');


慕虎7371278
浏览 560回答 3
3回答

慕姐4208626

有一个明确的案例可以看到.prop和.attr之间的差异考虑以下HTML:<form name="form" action="#">&nbsp; &nbsp; <input type="text" name="action" value="myvalue" />&nbsp; &nbsp; <input type="submit" /></form><pre id="return"></pre>和下面的JS使用jQuery:$(document).ready(function(){&nbsp; &nbsp; $("#return").append("$('form').prop('action') : " + $('form').prop('action') + '\r\n');&nbsp; &nbsp; $("#return").append("$('form').attr('action') : " + $('form').attr('action') + '\r\n');&nbsp; &nbsp; $("#return").append("document.form.action : " + document.form.action);});创建以下输出:$('form').prop('action') : [object HTMLInputElement]$('form').attr('action') : #document.form.action : [object HTMLInputElement]
打开App,查看更多内容
随时随地看视频慕课网APP