gpt4 book ai didi

javascript - 获取页面的 html 源代码,包括由 Jquery 或 Javascript 动态创建的元素

转载 作者:行者123 更新时间:2023-11-28 04:05:17 25 4
gpt4 key购买 nike

此类问题之前已经回答过,但我仍然没有得到合适的解决方案。我的方法是获取“body”标签及其所有子标签(动态创建)的 html 源代码,然后将它们保存在 session 存储中。这样页面就可以在这个缓存的帮助下重新加载数据。

我已经完成了几乎所有的事情,只是坚持获取 html 源代码。

我可以通过以下方式获取 html 代码:

console.log($('body').html());
console.log(document.body.innerHTML);

body 标签是这样的:

    <body>
<input type="button" id="btnconsole" value="Get Html">
<div id="divcontainer" style="background-color:blue; height:100%; width:100%;">
<input type="text" id="textbox">
</div>
</body>

但我没有得到输入标签的“值”字符串。为了更好的理解:执行以下代码:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btnconsole").on('click',function(){
console.log($('body').html());
//console.log(document.body.innerHTML);
});
});
</script>
</head>
<body>
<input type="button" id="btnconsole" value="Get Html">
<div id="divcontainer" style="background-color:blue; height:100%; width:100%;">
<input type="text" id="textbox">
</div>
</body>
</html>

现在在文本框中写一些东西,然后按“获取 Html”按钮。现在检查控制台。将有 html 源,但“文本框”值将不存在。

我知道我们可以通过 .value 获取输入值,但这将是不完整的解决方案。我正在寻找一些代码,通过这些代码我们可以获得 body 标签的完整源代码,包括动态创建/修改元素的值和属性。

最佳答案

我完全同意@nnnnnn 对这个问题的评论...

I wouldn't try to save application state by saving HTML, I'd be looking at keeping the application state in a JS object and then save a serialised version of that object (JSON). Then restore state by recreating HTML from the values in the state object as required.



但是,您可以执行以下操作来实现您想要的 - 这可能是我一段时间以来看到的最狡猾的事情......(不推荐)......

$(document).ready(function() {
$("#btnconsole").on('click', function() {
$("input").each(function() {
$(this).attr("value", $(this).val());
});
console.log($('body').html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btnconsole" value="Get Html">
<div id="divcontainer" style="background-color:blue; height:100%; width:100%;">
<input type="text" id="textbox" value="initial">
</div>

jquery html() does not return changed values

关于javascript - 获取页面的 html 源代码,包括由 Jquery 或 Javascript 动态创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992558/

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