[英]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.