简体   繁体   English

如何使用jQuery仅删除标记?

[英]How to remove only tag using jQuery?

I want to remove the span using jQuery, I have tried the .unwrap(); 我想用jQuery删除span,我试过.unwrap(); but it's not working. 但它不起作用。

<div>
<ul>
<li><a href="#"><span>link</span></a></li>
<li><a href="#"><span>link</span></a></li>
</ul>
</div>

Obviously, unwrap doesn't work as the span s only have text nodes inside them and jquery doesn't handle text nodes too well... this works however (you could use also jQuery.text instead of jQuery.html if you're sure that the span only contains text): 显然, unwrap不起作用,因为span只有文本节点在其中,而jquery不能很好地处理文本节点......但是这有效(如果你是的话,你可以使用jQuery.text而不是jQuery.html确保span只包含文本):

$('li a span').replaceWith($('li a span').html());

Working example 工作实例

Edit : Actually, it seems that unwrap works as well if you use jQuery.contents to work around the jquery's inability to directly select text nodes: 编辑 :实际上,如果你使用jQuery.contents来解决jquery无法直接选择文本节点的问题,那么unwrap似乎也可以工作:

$('li a span').contents().unwrap();
$('li').find('span').remove();

or 要么

$('li').find('span').detach();

If you want to remove the wrapping only, try 如果您只想删除包装,请尝试

var buffer = $('li').find('span').text();
$('li').find('span').parent().html(buffer);

Unwrap should work. 打开应该工作。 It's possible you're not successfully selecting the span which you wish to unwrap. 您可能无法成功选择要展开的跨度。 You can try the following code which should select that span successfully: 您可以尝试以下代码,该代码应成功选择该范围:

$("li a span").unwrap()

It's a bit unclear from your question what exactly you're trying to do. 从你的问题中有点不清楚你到底想要做什么。 It's also unclear whether you're having trouble with the selectors or with the jquery api. 目前还不清楚你是否遇到了选择器或jquery api的问题。 To get a better handle on jquery's selectors I recommend you install firebug and firequery , as it can really help you understand what you're selecting. 为了更好地处理jquery的选择器,我建议你安装firebugfirequery ,因为它可以真正帮助你理解你所选择的内容。

$("span").each(function() {
    var content = $(this).text();
    $(this).remove();
    $("a").html(content);
});

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

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