使用 element.outerHTML
时,我无法看到 input
元素的 value
属性。问题在于所有输入类型; HTML 示例:
<input type="text" id="copy-paste-textarea" />
JavaScript 示例:
<script type="text/javascript">
$('#copy-paste-textarea').on('click', function(e) {
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// Output: <input id="copy-paste-textarea" type="text">
$(this).val('hello!');
$(this).addClass('world!');
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// Output: <input id="copy-paste-textarea" class="world!" type="text">
});
</script>
当我运行上面的代码时,我看到 addClass() 的更改反射(reflect)在 this.outerHTML 中,但 val() 的更改没有反射(reflect)。但是 - 我看到该字段确实正在填充值。我希望输出是这样的:
// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">
html() 函数产生相同的结果。我想要一个适用于任何输入类型(选择、文本区域等)的解决方案。
这里的类似答案仅适用于文本区域:Cannot get outerHTML/value of a dynamically added textarea
最佳答案
这是因为元素具有“属性”,仅在内存中存储由 JavaScript DOM 对象表示的动态信息,并且它们还具有“属性”,其中元素的实际标记记录在内存中并可通过 HTML 解析器访问。
- JQuery 的
.val()
方法将数据写入仅内存中的属性。 - 要获得所需的内容,您必须使用以下命令设置
值
属性 JQuery 的.attr()
方法。
属性和特性之间微妙但重要的区别导致了 JQuery 的 .prop()
之间的混淆。 和 .attr()
方法。
$('#copy-paste-textarea').on('click', function(e) {
console.log("input field's outerHTML???" + this.outerHTML + "|");
// You must set the attribute for it to be picked up in the HTML
$(this).attr("value", "hello!");
$(this).addClass('world!');
console.log("input field's outerHTML???" + this.outerHTML + "|");
});
// For a textarea, you need to get the content of the tags with .text()
$('textarea').on('click', function(e) {
console.log("Text area's outerHTML???" + this.outerHTML + "|");
// You must set the attribute for it to be picked up in the HTML
$(this).text("value", "hello!");
$(this).addClass('world');
console.log("Text area's outerHTML???" + this.outerHTML + "|");
});
.world {
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="copy-paste-textarea">
<textarea></textarea>
关于javascript - $(element).val ('newvalue' ) 未反射(reflect)在 element.outerHTML 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47316925/