【问题标题】:Help in jquery selectorsjquery 选择器的帮助
【发布时间】:2011-09-09 23:36:04
【问题描述】:

您好,请参考以下 HTML 代码:

<div id="content">
    <p>
      <font size='2'>
        <img src="something.jpg" width="500" height="500" />
        this is the text content. this is the text content. this is the text content...
      </font>
    </p>
</div>

这是从我的 Web 应用程序的管理部分生成的 html 代码。我不能修改它,也不能改变上面代码的结构。它是动态生成的。

我需要使用 jquery wrap() 方法将文本内容包装在一个 html 元素中,这样我就可以在文本内容上而不是在 img 元素上放置一些 css。

注意:id 为“content”的 div 元素是我自己的,我只能使用 HTML 访问它。

请帮忙怎么做?

谢谢

【问题讨论】:

  • 我试过这个 var elm = $("#content p font").children(":not(img)").wrap("
    ");

标签: javascript jquery html css jquery-selectors


【解决方案1】:

这里是jQuery方式

$("p > font")
  .contents()
  .filter(function() {
    return this.nodeType == 3;
  }).wrap('<span style="color:#FF0000" />');

You can Demo it herehttp://www.jsfiddle.net/K8WNR/

【讨论】:

    【解决方案2】:

    不确定您是否可以使用 jQuery 做到这一点。但是,如果您使用原始 JavaScript,您可以查看节点并检查它们的 nodeType,其中 1 是元素,3 是文本。所以说f是你的字体元素:

    for (var i=0; i < f.childNodes.length; i++) {
        if (f.childNodes[i].nodeType == 3) {
            var text = f.nodeValue;
            // Remove the text node, insert a new span node and plug in the text.
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试这个……

      $(function() {  
          $("#content").find("p > font").each(function() {
          var $this = $(this).wrapInner(document.createElement("div"));
          var $img = $this.find('img').remove();
          $this.prepend($img);
          })
      }); 
      

      这将返回这个...

      <p>
         <img height="500" width="500" src="something.jpg">
          <div>
              this is the text content. this is the text content. this is the text content...
          </div>
      </p>
      

      【讨论】:

      • 谢谢,但我只想包装“文本内容”而不是 img 元素。
      • 好的,我修改了上面的代码。 John 的示例将产生一些额外的空 标签,但仍然有效。 -- 祝你好运
      猜你喜欢
      • 2011-09-17
      • 2011-04-03
      • 2011-04-27
      • 2011-03-03
      • 1970-01-01
      相关资源
      最近更新 更多