javascript - jquery.html() 表单的奇怪行为

标签 javascript jquery html

我有以下 html:

<div class="copy_me_text">
    <div>
        <input type="text" name="name" />
        <input type="hidden" name="id" />
    </div>
</div>

<div class="copy_me_hidden">
    <div>
        <input type="hidden" name="name" />
        <input type="hidden" name="id" />
    </div>
</div>

下面的js代码:

var $cloned_text = $('.copy_me_text').clone();
$cloned_text.find('input[name="name"]').val("SOMETHING");
$cloned_text.find('input[name="id"]').val("SOMETHING");
console.log($cloned_text.html());

var $cloned_hidden = $('.copy_me_hidden').clone();
$cloned_hidden.find('input[name="name"]').val("SOMETHING");
$cloned_hidden.find('input[name="id"]').val("SOMETHING");
console.log($cloned_hidden.html());

输出对我来说很奇怪:

<div>
    <input name="name" type="text">
    <input value="SOMETHING" name="id" type="hidden">
</div>
<div>
    <input value="SOMETHING" name="name" type="hidden">
    <input value="SOMETHING" name="id" type="hidden">
</div>

我还创建了 jsFiddle example . 这是正确的行为吗?我不明白,为什么在 .html() 函数中,没有返回 input type="text" 的值。

最佳答案

这不是一个奇怪的 jQuery 行为,它是一个奇怪的 DOM 效果。 jQuery.val() 除了设置 value 什么都不做<input>的属性(property)元素。 “属性”是指 DOM 属性 而不是节点属性 - 参见.prop() vs .attr()为了区别。

.html() 方法,它返回 innerHTML DOM 的序列化,预计只显示元素的属性——它们的属性是无关紧要的。这是默认行为,当您想要序列化输入值时,您需要将它们显式设置为属性 - $input.attr("value", $input.prop("value")) .

那么为什么简单 val()处理隐藏的输入元素?原因是 HTML 规范。有reflecting IDL attributes ,其中 DOM 属性与节点属性耦合,但 value属性不是这些。然而,value IDL attribute有特殊模式,在其中它有不同的 react 。引用规范:

The attribute is in one of the following modes, which define its behavior:

value

On getting, it must return the current value of the element. On setting, it must set the element's value to the new value, set the element's dirty value [… and do a lot of other stuff].

默认

On getting, if the element has a value attribute, it must return that attribute's value; otherwise, it must return the empty string. On setting, it must set the element's value attribute to the new value.

[“默认/打开”和“文件名”模式]

找出不同之处?现在,让我们看看 statestype attribute .实际上,如果我们检查Bookkeeping details 部分,我们会注意到在 hidden state 中,

The value IDL attribute applies to this element and is in mode default

‐ 而在所有其他(文本)状态中,模式是“值”。


长话短说:

(仅)在 <input type="hidden">元素,设置 value DOM 属性( input.value = … , $input.val(…) , $input.prop("value", …) )也设置了 value属性并使其可序列化为 innerHTML/.html() .

关于javascript - jquery.html() 表单的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440219/

相关文章:

javascript - 如何使 <tr> 充当固定的顶部栏?

javascript - Bootstrap 下拉菜单嵌套在表单 : tabindex breaks on enter 中

javascript - 使用数据值/提取选定的 "Tag"的值

javascript - 从 javascript 返回一个数组

javascript - 访问 Polymer 中的原生 HTML 元素

javascript - $ionicView.enter 和 cache :false 有什么区别

javascript - 在 d3 的 forcelayout 算法中禁用力

javascript - php json 到 javascript json 格式不符合要求的结果

html - 如何在html和css中将图像放在圆圈内?

html - 如何像sass中的变量一样获取 child 的数量