[英]Why is the jquery method html() still have old content when using val() to update input value
<div id="test-node">
<input id="input-test" type="text" name="" value="old old old">
</div
…… ……
$("#input-test").val("new new new");
console.log($("#input-test").html());
The console log is <input id="input-test" type="text" name="" value="old old old">
控制台日志为
<input id="input-test" type="text" name="" value="old old old">
Why does val()
not update the input vallue? 为什么
val()
不更新输入值? When I use attr()
, it does work well. 当我使用
attr()
,它运行良好。
The val()
method will just update the value
property of the element and not the value
attribute. 的
val()
方法将只是更新value
的元素的属性,而不是value
属性。
To get the current value use val()
method without any argument. 要获取当前值,请使用不带任何参数的
val()
方法。
$("#input-test").val("new new new");
// to get the value use the val() method
console.log($("#input-test").val());
$("#input-test").val("new new new"); console.log($("#input-test").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test-node"> <input id="input-test" type="text" name="" value="old old old"> </div>
attr()
method.
attr()
方法更新属性。
$("#input-test").attr('value', "new new new"); console.log($("#itest-node").html());
$("#input-test").attr('value', "new new new"); console.log($("#input-test")[0].outerHTML); console.log($("#test-node").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test-node"> <input id="input-test" type="text" name="" value="old old old"> </div>
$("#input-test").val("new new new");
This line of code updates the value of the input
, not change the element itself. 这行代码将更新
input
的值 ,而不更改元素本身。 Since you execute this function, you will notice on the browser screen that input
will have a value new new new
由于执行了此功能,因此您将在浏览器屏幕上注意到
input
将具有值new new new
If you want to change to value
attribute of the input
element, you should do something like: 如果要更改
input
元素的value
属性,则应执行以下操作:
$("#input-test input").attr("value", "new new new");
Why? 为什么? Because the value attribute and the value property of an element are not the same once any user input or programmatic changes are made
因为一旦进行任何用户输入或编程更改,元素的value属性和value属性都不相同
The value attribute is only used by browser to be able to set the value property if applicable. value属性仅由浏览器用来设置value属性(如果适用)。
Try using val()
as getter: 尝试使用
val()
作为吸气剂:
$("#input-test").val("new new new");
console.log($("#input-test").val());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.