使用 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(( 的更改反映在 this.outerHTML 中,但 val(( 的更改则没有。 但是 - 我看到该字段确实填充了这些值。 我希望输出是这样的:
// Output: <input id="copy-paste-textarea" value="hello!" class="world!" type="text">
html(( 函数产生相同的结果。 我想要一个适用于任何输入类型(选择、文本区域等(的解决方案。
这里的类似答案仅适用于文本区域:无法获取动态添加的文本区域的 outerHTML/值
这是因为元素具有"属性",它们仅将动态信息存储在由JavaScript DOM对象表示的内存中,并且它们还具有"属性",其中元素的实际标记记录在内存中,并且可以通过HTML解析器访问。
- JQuery 的
.val()
方法将数据写入仅内存中的属性。 - 要获得所需的内容,必须
value
使用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>