【问题标题】:jQuery wrap span around textjQuery环绕文本
【发布时间】:2012-11-23 11:03:24
【问题描述】:

我有以下

<div><span class="myspan">hello</span> this text has no span </div>

在 jQuery 中,如何包装 div 或围绕“此文本没有跨度”文本?

【问题讨论】:

  • 如果我是你,我会将@Vision 标记为答案。必须感谢任何痛苦!

标签: javascript jquery text


【解决方案1】:

对于您当前的示例,这是我的单行解决方案:

$("div span").detach().prependTo($("div").contents().wrap("<span />").end());

演示: http://jsfiddle.net/awwTA/

【讨论】:

  • 这就是我喜欢jquery的原因!
  • @Behnam Esmaili 是也不是,维护起来会让人头疼,但这个例子很好
  • 没有什么比时间更有价值的了。jquery 节省了我的时间。
【解决方案2】:

这不是最好的解决方案,但可以帮助您...

<div id="myDiv"><span class="myspan">hello</span> this text has no span </div>

var div = $('div#myDiv');
var span = $('span.myspan');
div.remove(span);
div.html($('<span></span>').text(div.text()));

我猜你知道我想要做什么

【讨论】:

    【解决方案3】:

    您可以在父 div 中搜索任何文本 (nodeType:3) 元素,然后将每个文本包装在另一个 div 中。见下例:

    $('#myDiv').contents().filter(function(){
       return this.nodeType === 3;
    }).wrapAll("<div class='red' />");
    .red { color: red; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myDiv"><span class="myspan">Hello</span> this text has no span </div>

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2019-01-26
      相关资源
      最近更新 更多