为什么jquery .val()仅更改隐藏输入字段的value属性? [英] Why does jquery .val() only change value attribute for hidden input fields?

查看:113
本文介绍了为什么jquery .val()仅更改隐藏输入字段的value属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用一些非常简单的jQuery来更改文本字段的值:

We're using some very simple jQuery to change the value of our text field:

<input type="text" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);

这会更改浏览器中显示的值,但是不会更改源代码中文本字段的value属性.

This changes the value displayed in the browser, does NOT however change the value attribute of our text field in the source code.

现在,考虑一下:

<input type="hidden" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);

将输入类型更改为隐藏,值属性也会更改!

Change the input type to hidden and the value attribute DOES change!

1.这是否意味着我们必须执行以下操作来更改显示在浏览器中的输入字段的值及其在源代码中的value属性??

1.Does this mean we have to do the following to change our input field's value displayed in the browser AND its value attribute in the source code?:

<input type="text" name="rabatt" id="sonderrabatt" value="">
var sonderrabatt = 10;
$('#sonderrabatt').val(sonderrabatt);
$('#sonderrabatt').attr('value',sonderrabatt);

2..val()为什么对type = hidden无效,而对于type = text输入字段则无效?

2.Why does .val() work for type=hidden and NOT for type=text input fields?

推荐答案

.val()更改元素属性的值,而不是属性的值.属性是html在初始渲染中显示的内容,属性包含DOM object 中的实际值,该值可以多次更改,但在初始渲染后可能不会显示在HTML中.

.val() changes the elements property value, not attribute value. Attributes are what the html shows on initial render and properties contain the actual values in the DOM object which can be changed many times but may not be displayed in HTML after initial render.

.val(myValue).prop('value', myValue)

使用纯JavaScript

In plain JavaScript

element.value = myValue; // set property on DOM object
element.setAttribute('value', myValue); // set attribute on HTML element

请记住

  • DOM元素(HTML)->属性

  • DOM elements (HTML) -> attributes

DOM对象(JS)->属性

DOM objects (JS) -> properties

相关

这篇关于为什么jquery .val()仅更改隐藏输入字段的value属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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