gpt4 book ai didi

javascript - 为什么我使用 JQuery 只获取文本而不是 HTML?

转载 作者:行者123 更新时间:2023-11-28 12:52:28 26 4
gpt4 key购买 nike

我有一个 H1 标签,我想在单击按钮时获取此元素的 HTML() 但现在只获取文本而不是 HTML。我怎样才能获得正确的 HTML?

我的代码:-

$(function(){
$('button').click(function(){
alert($('h1').html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 style="color:indianRed">Heading 1</h1>

<button>Click</button>

最佳答案

您应该使用outerHTML :

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

$(function(){
$('button').click(function(){
alert($('h1').get(0).outerHTML);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 style="color:indianRed">Heading 1</h1>

<button>Click</button>

关于javascript - 为什么我使用 JQuery 只获取文本而不是 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com