为什么jQuery val()函数不更新属性“值"? [英] Why does jQuery val() function not update attribute 'value'?

查看:284
本文介绍了为什么jQuery val()函数不更新属性“值"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在完成网站后遇到了这种问题,因为我必须在基于ajax的页面中实现历史记录(这需要用html更新某些位置(其中包括带有简单文本 inputs 的表单-那就是问题所在-他们没有分配值,因为它们的值是由val()而不是attr()设置的-所在)).我注定要替换掉所有来自

I came across with this issue way after I completed the website since I had to implement history in ajax based page (which requires to update certain places with html (which includes forms with simple text inputs - that's where the problem - they don't get their values assigned, because they have their values set by val() and not by attr() - lies)). Am I doomed to have to replace all javascript from

$('#xxx').val('someValue');

$('#xxx').attr('value', 'someValue');

还是有希望绕过这个?

or there is some hope to bypass this?

此处一个非常简单的示例.如您在对话框中所看到的,属性 value 未在html代码中设置.

A pretty trivial example here. As you can see in the dialog, attribute value is not set in html code.

推荐答案

它使用基础本机element.value = 'someValue',该本机当然会设置元素的值 property

It uses the underlying native element.value = 'someValue' that of course sets the value property of the element

element.property_to_set = 'new_value';

因此它不会更改属性,即

so it does not change the attribute, that would be

element.setAttribute('value', 'someValue')

这是attr()在内部执行的操作,而prop()会更改属性,就像val()一样.
它更改属性的原因是,该属性是表单提交中使用的属性,通常也是用于在javascript中取回值的属性,因此,坚持使用属性而不是属性是有道理的,因为该属性通常仅用于设置属性的初始值,并且以后使用javascript更改属性不会更新该属性,这与您拥有的属性相反,并且会影响所有表单提交并成为一个主要问题.

which is what attr() does internally, while prop() changes the property, just like val().
The reason it changes the property, is that the property is what is used in a form submit, and it's normally what is used to get the value back in javascript as well, so it makes sense to stick with the property and not the attribute, as the attribute is normally just used to set the initial value of the property, and changing the attribute later with javascript does not update the property, which would be the opposite problem of the one you're having, and it would affect all form submits and be a major issue.

这篇关于为什么jQuery val()函数不更新属性“值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆