如何获取与当前DOM树相对应的HTML? [英] How do I get HTML corresponding to current DOM tree?

查看:208
本文介绍了如何获取与当前DOM树相对应的HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery(html)。html()似乎检索大部分,除了包装标签。



DOM被大量修改,所以原始来源是没有太多用处。




  • 是否可靠?

  • 这是一个好主意采取jQuery的输出并围绕它我可以在这里看到至少一些doctype问题,并且包含不应该重新运行的脚本。

  • 任何更好的方法?



编辑:jQuery()。append(jQuery(html)。clone()).html()几乎可以工作,除了doctype。有没有一个简单的方法来获得它?



编辑2:我需要doctype主要获得适当的奇怪/几乎标准/标准模式。 document.compatMode有一半它是否足够?

解决方案

jQuery使用 innerHTML 获取HTML。您不会使用此属性获取确切的DOM状态。例如,输入值的内容或选择框的状态将不会保持不变,除非您正确修改它在调用 innerHTML 之前。



这是什么 wrap 你在说什么?对于大多数情况,innerHTML应该可以正常工作。



例如,我使用这个代码为选择输入框。

  //它是defaultValue,所以我们可以使用innerHTML 
$(#divContentInside input)。each(function(){
this.defaultValue = this.value;
});
//遍历每个选择并替换
//它的选择,所以我们可以使用innerHTML
$(#divContentInside select>选项)。each(function(){
if(this.selected){
this.setAttribute(selected,true);
} else {
this.removeAttribute(selected);
}
});

我没有发现其他元素的状态一致性问题,但可能有。 >

jQuery("html").html() seems to retrieves most of it, except for the wrapping tag.

DOM is heavily modified, so original source is of not that much use.

  • Is it reliable?
  • Is it a good idea to just take jQuery's output and wrap ... around it? I can see at least some doctype problems here, and inclusion of scripts which shouldn't be rerun.
  • Any better way?

EDIT: jQuery("").append(jQuery("html").clone()).html() almost works, except for doctype. Is there an easy way to get it?

EDIT 2: I need the doctype mostly to get proper quirk/almoststandards/standards mode. document.compatMode has half of it, is it enough?

解决方案

jQuery uses innerHTML to get the HTML. You're not going to get the exact DOM state using this attribute. For example the content of input values or the state of a select box will not stay the same unless you properly modify it before calling innerHTML.

What is this wrapping tag you're talking about? For most of it, innerHTML should work fine.

For example, I use this code for the state of select and input boxes.

// it's defaultValue so we can use innerHTML
$("#divContentInside input").each(function () {
    this.defaultValue = this.value;
});
// go through each select and replace
// it's selection so we can use innerHTML
$("#divContentInside select > option").each(function () {
    if (this.selected) {
        this.setAttribute("selected", true);
    } else {
        this.removeAttribute("selected");
    }
});

I haven't found issues with state consistency of other elements, but there probably is.

这篇关于如何获取与当前DOM树相对应的HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆