javascript - 选择html元素的前缀和后缀标签

标签 javascript jquery html dom tree-traversal

我要解决的问题是选择所选 html 元素的特定前缀和后缀。一个小例子应该描述我正在尝试做的事情。假设我们有以下 html 源代码:

<div class="box1">
  <div class="tutlogo">
    <a class="box" href="sql/default.asp" target="_top">
      <div class="image" style="background-color:#FF9900;"></div>
      <h1>SQL</h1>
    </a>
  </div>
</div>
<div class="tutbuttons">    
  <a class="btn" href="sql/default.asp" target="_top">SQL Tutorial</a>
  <a class="btn" href="sql/sql_quickref.asp" target="_top">SQL Reference</a>
</div>
<div class="box1">
  <div class="tutlogo">
    <a class="box" href="php/default.asp" target="_top">
      <div class="image" style="background-color:#41BC81;"></div>
      <h1>PHP</h1>
    </a>
  </div>
  <div class="tutbuttons">
    <a class="btn" href="php/default.asp" target="_top">PHP Tutorial</a>
    <a class="btn" href="php/php_ref_array.asp" target="_top">PHP Reference</a>
  </div>
</div>          

假设我选择了 <h1>PHP</h1>元素。我试图提取为该元素的“前缀”的是 n <h1> 之前的 html 标签标签。鉴于 n是5,那么我要提取的作为前缀的就是序列:</div><div><a><div><div> .我想分别提取 <h1>PHP</h1> 之后的 5 个 html 标签元素作为后缀。在本例中为:</a></div><div><a></a> .

我尝试使用 tree traversal jquery 的方法来完成工作但是,这样我就无法获得结束的 html 标签。我也在谷歌上搜索了一个解决方案,但找不到适合我需要的任何东西。也许有人已经这样做了,可以告诉我如何提取前缀、后缀标签,或者可以指出正确的方向。也许它真的很微不足道,我只是想得太复杂了。

无论如何感谢您的帮助。

最佳答案

我不认为这是微不足道的,这应该会让你对之前的努力感觉良好。

您可能需要一些树遍历,无论您最终如何进行。前几天我正在构建一个自动工具提示创建插件,所以我想到了这类东西。

这是我一起破解的 - http://jsfiddle.net/naazkc1v/

这不是最终确定的解决方案,但它可以按原样工作并且可能会帮助您实现所需。

  1. 定义要抓取标签的元素 var initialEl = $("h1")[0]
  2. 它向上导航文档树,如果遇到 $('body')、$('html') 或 $(document) 则停止
  3. 它采用该根元素并递归地删除 html 标签上的所有属性并清空文本节点
  4. 它在新的精简 HTML 中找到原始元素的 HTML,并返回它前后的字符串。

例子

使用这个 HTML

<div class="box1">
  <div class="tutlogo">
    <a class="box" href="php/default.asp" target="_top">
      <div class="image" style="background-color:#41BC81;"></div>
      <h1>PHP</h1>
    </a>
  </div>
  <div class="tutbuttons">
    <a class="btn" href="php/default.asp" target="_top">PHP Tutorial</a>
    <a class="btn" href="php/php_ref_array.asp" target="_top">PHP Reference</a>
  </div>
</div>    

最后的 3 个控制台日志将是

<div><a><div></div>
<h1>PHP</h1>
</a></div><div><a></a><a></a></div>

与您想要的解决方案相比的问题:

目前不保证目标前后都会有n标签。编写解析器来去除额外的标签应该很容易。但是,如果根父节点不包含足够的标签,则获取额外标签将需要获取我们发现的根节点的兄弟节点,在该兄弟节点上运行整个函数,然后从其返回值中解析出必要的标签。

资源

完整的 Javascript

$(function(){

    jQuery.fn.removeAttributes = function() {
      return this.each(function() {
        if (this.attributes){
            var attributes = $.map(this.attributes, function(item) {
              return item.name;
            });
            var img = $(this);
            $.each(attributes, function(i, item) {
              img.removeAttr(item);
            });
        }
      });
    }

    var initialEl = $("h1")[0],
        html = $("html")[0],
        body = $("body")[0],
        el = initialEl;

    function nodeInBody(node){
        return node.parentNode &&
               node.parentNode != document &&
               node.parentNode != html &&
               node.parentNode != body;
    }

    while ( nodeInBody(el) ){
        el = el.parentNode;
    }

    var $el = $(el),
        //This assumes there's only ONE text node within the original element
        //If you have any other elements inside the element you're targetting,
        //this will fail
        $initialTextNode = $(initialEl).contents()[0];

    function removeAttributesFromChildren(el){
        $(el).contents().each(function(i,el){
            // Emptying Text Nodes if they're not our saved one
            if ( el.nodeType == 3 && el !== $initialTextNode) el.nodeValue = "";
            //Call the jQuery plugin we defined earlier
            $(el).removeAttributes();
            // Call this function on the element
            removeAttributesFromChildren(el);
        });
    }

    removeAttributesFromChildren(el);

    var html = $(el).html(),
        initialElHTML = initialEl.outerHTML;

    var start = html.indexOf(initialElHTML);

    // If our original item's HTML is contained in the html string
    if ( start > -1 ){
        // Grab the strings before and after it
        var end = start+initialElHTML.length,
            before = html.substring(0,start),
            word = html.substring(start,end),
            after = html.substring(end);

            console.log(before);
            console.log(word);
            console.log(after);

    }

});

关于javascript - 选择html元素的前缀和后缀标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25595480/

相关文章:

html - 屏幕外的 "hiding"个对象是否会导致性能损失达到荒谬的程度?

javascript - 无法使标签在可缩放的 d3 sunburst 上工作

javascript - 为什么在 ES5 中变量对象被改为词法环境?

jquery - 在 Firefox 和 IE 中使用 jquery 防止 onbeforeunload 警报

javascript - Jquery 使用 attr() 返回 object 对象更改 HTML 属性

javascript - 如何在多个标签中添加与类名一起使用的 ID?

html - 直接从 django-template 发送电子邮件

Javascript - 替换括号之间的字符串,但括号应该保留

javascript - 如何将元素定位在表格可见区域的中间?

javascript - 使用jquery提取特定文本