为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery attr vs道具?

jQuery attr vs道具?

慕虎7371278 2019-11-14 15:34:18
现在,这不仅仅是另一个问题了。我做了一些测试(http://jsfiddle.net/ZC3Lf/),修改了prop和attr,<form action="/test/"></form> 输出为:1)道具修改测试道具:http://fiddle.jshell.net/test/1属性:http://fiddle.jshell.net/test/12)属性修改测试属性:http://fiddle.jshell.net/test/1属性:/test/13)属性然后进行道具修改测试属性:http://fiddle.jshell.net/test/11属性:http://fiddle.jshell.net/test/114)属性然后进行属性修改测试属性:http://fiddle.jshell.net/test/11属性:http://fiddle.jshell.net/test/11现在,就我所知,我对两件事感到困惑:道具:通过JavaScript进行任何修改后的当前状态值:网页加载时html中定义的值。现在,如果这是正确的,为什么修改prop似乎使action完全合格,反之为什么不修改属性?为什么修改propin 1)修改属性,那对我没有意义?为什么修改attrin会2)修改属性,它们是要以这种方式链接?测试代码的HTML的JavaScriptvar 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 />');//resetelement.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 />');//resetelement.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 />');//resetelement.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 />');
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

有一个明确的案例可以看到.prop和.attr之间的差异


考虑以下HTML:


<form name="form" action="#">

    <input type="text" name="action" value="myvalue" />

    <input type="submit" />

</form>

<pre id="return">

</pre>

和下面的JS使用jQuery:


$(document).ready(function(){

    $("#return").append("$('form').prop('action') : " + $('form').prop('action') + '\r\n');

    $("#return").append("$('form').attr('action') : " + $('form').attr('action') + '\r\n');

    $("#return").append("document.form.action : " + document.form.action);

});

创建以下输出:


$('form').prop('action') : [object HTMLInputElement]

$('form').attr('action') : #

document.form.action : [object HTMLInputElement]


查看完整回答
反对 回复 2019-11-14
  • 3 回答
  • 0 关注
  • 553 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信