开发者

Newly created input-element ignoring attribute changes

开发者 https://www.devze.com 2023-02-19 22:25 出处:网络
Why does $(\"<input type=\'text\' value=\'Foo\' />\").val(\"Bar\") result in an object (as shown in the debugger console):

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") shou开发者_如何学运维ld 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.


Would you do this? http://jsfiddle.net/mazzzzz/q6bfp/1/


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消