为什么jquery .val()只更改隐藏输入字段的value属性?

Ric*_*ler 3 html jquery

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

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

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

现在,考虑一下:

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

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

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

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

2.为什么.val()适用于type = hidden而不适用于type = text输入字段?

Mig*_*ota 11

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

.val(myValue) 是简写 .prop('value', myValue)

在纯JavaScript中

element.value = myValue; // set property on DOM object
element.setAttribute('value', myValue); // set attribute on HTML element
Run Code Online (Sandbox Code Playgroud)

只记得

  • DOM元素(HTML) - >属性

  • DOM对象(JS) - >属性

有关