[英]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());
控制台日志为<input id="input-test" type="text" name="" value="old old old">
为什么val()
不更新输入值? 当我使用attr()
,它运行良好。
的val()
方法将只是更新value
的元素的属性,而不是value
属性。
要获取当前值,请使用不带任何参数的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()
方法更新属性。
$("#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");
这行代码将更新input
的值 ,而不更改元素本身。 由于执行了此功能,因此您将在浏览器屏幕上注意到input
将具有值new new new
如果要更改input
元素的value
属性,则应执行以下操作:
$("#input-test input").attr("value", "new new new");
为什么? 因为一旦进行任何用户输入或编程更改,元素的value属性和value属性都不相同
value属性仅由浏览器用来设置value属性(如果适用)。
尝试使用val()
作为吸气剂:
$("#input-test").val("new new new");
console.log($("#input-test").val());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.