简体   繁体   English

jQuery删除包装元素

[英]jQuery removes wrapping element

I am loading a html file with jquery $.get and wrap the response. 我正在用jquery $ .get加载一个html文件并包装响应。 But jQuery removes my wrapper . 但是jQuery删除了我的包装器。

I made the following example which demonstrates my problem: https://jsfiddle.net/pwm76bp6/ 我制作了以下示例来演示我的问题: https : //jsfiddle.net/pwm76bp6/

Everyone who dont want to open the link here is the example code: 每个不想在此处打开链接的人都是示例代码:

alert($('<div><div>Hallo</div></div>').html());

I would expect that the whole string should be alerted. 我希望应该对整个字符串进行警告。 Whats the problem here? 这里有什么问题?

您需要阅读outerHTML属性。

 console.log($('<div><div>Hallo</div></div>').prop('outerHTML')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

用一个元素动态包装它,然后获取被包装元素的html()。

alert($('<div><div>Hallo</div></div>').wrap("<div></div>").parent().html());

It doesn't remove your wrapper. 它不会删除您的包装。 jQuery html() does return the contents of an element. jQuery html()确实返回元素的contents

When you do $('<div>my content</div>') you creating an element, then you get the inner html with html() which is then alerted in your example. 当您执行$('<div>my content</div>')您将创建一个元素, 然后使用html()获取内部html,然后在示例中将其警告。

With your code you will get the html of your outer element <div> . 使用您的代码,您将获得外部元素<div>html And the content of the outer <div> is <div>Hallo</div> . 外部<div>的内容是<div>Hallo</div>

You can do what you want with a default property: 您可以使用默认属性执行所需的操作:

alert($('<div><div>Hallo</div></div>')[0].outerHTML);

the function "html" does return the html content of a given element. 函数“ html”确实返回给定元素的html内容。 In your case "html()" returns the content of the outer div, which excludes the outer itself. 在您的情况下,“ html()”返回外部div的内容,其中不包括外部本身。

You may can overcome this by wrapping your html like: 您可以通过包装html来克服这一问题:

var html = '<div><div>Hallo</div></div>';
var outerHtml = $(html).wrap('<div />').parent().html();

hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM