【问题标题】:using jquery to get the content of a <tag>使用 jquery 获取 <tag> 的内容
【发布时间】:2014-03-26 19:07:59
【问题描述】:

我有一个关于“未知”标签的问题。我的意思是没有在 HTML 中定义的标签。

请参阅以下块:

<div class='container'>
  <element definition>
</div>

然后使用 jquery 我想获取所有 div 的孩子的列表,然后提取他们的内容。要做到这一点,不知道是我只有RegExp可以做,还是有一些jQuery函数可以搞定。

例如,定义一个函数set_tags_to_p(),将标签更改为&lt;p&gt;

【问题讨论】:

  • 您可以使用此 $("#container").text() 来获取所有标签的文本内容.. 并遍历子项,即使它们不是标准的 $("#container ").children().each(function() { ... });
  • 看来你要求的是两个不同的东西,我可以请你澄清一下吗?你的意思是问1.标签不标准时的树遍历,还是2.set_tags_to_p()这个函数怎么写?

标签: javascript jquery html regex dom


【解决方案1】:

你可以用p 替换子元素,就像这样很容易:

$('.container').children().replaceWith(function() {
    return '<p>' + $(this).html() + '</p>';
});

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

【讨论】:

    【解决方案2】:

    你可以这样做

    var element, elementHtml, pTag;
    element = $("element") // you can change the name
    elementHtml = element.html();
    pTag = $("<p>").html(elementHtml);
    

    【讨论】:

      【解决方案3】:
      $('.container').find('*').each(function () {
          $(this).replaceWith('<p>' + $(this).html() + '</p>')
      })
      

      jsFiddle example

      【讨论】:

        【解决方案4】:

        如果您知道要替换的标签的名称,您可以这样做:

        <div class="container">
            <up>Test</up>
            <down>Test</down>
            <left>Test</left>
            <right>Test</right>
            <broken>Test</broken>
        </div>
        
        $(function(){
          $('.container').children("up, down").replaceWith(function() {
            return '<p>' + $(this).html() + '</p>';
          });      
        });
        

        http://jsfiddle.net/JqY5R/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-11-16
          • 2012-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多