简体   繁体   中英

Newly created input-element ignoring attribute changes

Why does

$("<input type='text' value='Foo' />").val("Bar")

result in an object (as shown in the debugger console):

<input type="text" value="Foo">

Shouldn't the value be "Bar" now that I changed it?

My guess is that it has something to do with the element not being part of the document.
How can I work around this limitation?

I would like to avoid inserting the element into the document at that point. However, later code which uses attr("value") should get the correct result.

In this test the element is not inserting into the document and its value is "Bar", as expected. May be something wrong with the console.

OK - I finally found and resolved the issue:

Firstly, as pointed out in the comment, the HTML of detached elements (especially the attributes) does not seem to be kept in sync with the actual element properties. This happens after inserting the elements into the document.
This problem I am aware now caused me many headaches debugging my code and made it impossible to find the second one. Thanks for helping me discovering it!

Secondly, I am looping through the attributes of the elements using their "attributes" property.
A short illustration (without the loop):

var $input = $("<input type='text' value='Foo' />");
$input.val("Bar");     
alert($input.attr("value") + " - " + $input.get(0).attributes["value"].value);

This code alerts "Bar - Foo" as long as $input is not part of the document. I fixed this problem by replacing calls to attribute.value with calls to $element.attr(attribute.name) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM