javascript - $(element).val ('newvalue' ) 未反射(reflect)在 element.outerHTML 中

标签 javascript jquery

使用 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/

相关文章:

jquery - 滚动过去后如何使 div 内的元素变粘?

javascript - 如何使用 JQuery 淡入图像变化

javascript - 使用 javascript 动态添加图片。

javascript - × TypeError : Cannot read properties of undefined (reading 'getState' )

javascript 逻辑 else 如果不工作

javascript - 鼠标位置和偏移

javascript - 根据所选的下拉列表项从 MySQL 动态填充多个输入字段

javascript - Nodejs - 正确从其他文件调用方法

javascript - 了解 JavaScript - 资源

javascript - 为什么我无法使用 jQuery.parseJSON(json) 解析 json 字符串?