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

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

问题描述

我在完成网站后遇到了这个问题,因为我必须在基于 ajax 的页面中实现历史记录(这需要用 html 更新某些地方(包括带有简单文本的表单输入 -这就是问题所在 - 他们没有得到他们的值,因为他们的值是由 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');

还是有希望绕过这个?

一个非常简单的例子这里.正如您在对话框中看到的,属性 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天全站免登陆