选择以“x-”开头的标签在jQuery中 [英] Select tags that starts with "x-" in jQuery

查看:122
本文介绍了选择以“x-”开头的标签在jQuery中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择以x - 标记名称开头的节点,这是一个层次结构DOM树示例:

How can I select nodes that begin with a "x-" tag name, here is an hierarchy DOM tree example:

<div>
  <x-tab>
    <div></div>
    <div>
      <x-map></x-map>
    </div>
  </x-tab>
</div>
<x-footer></x-footer>

jQuery不允许我查询 $('x- *') ,有什么方法可以达到这个目的吗?

jQuery does not allow me to query $('x-*'), is there any way that I could achieve this?

推荐答案

没有本地方法可以做这个,性能最差,所以,你自己动手吧。

There is no native way to do this, it has worst performance, so, just do it yourself.

例子:

var results = $("div").find("*").filter(function(){
    return /^x\-/i.test(this.nodeName);
});

完整示例:

http://jsfiddle.net/6b8YY/3/

注意:(已更新,请参阅注释)

如果您想知道我为何使用这种方式检查标记名称,请参阅:

JavaScript:不区分大小写的搜索 < br>
并查看评论。

If you are wondering why I use this way for checking tag name, see:
JavaScript: case-insensitive search
and see comments as well.

此外,如果您想知道 find 方法而不是添加到选择器,因为选择器从右而不是从左侧匹配,所以最好将选择器分开。我也可以这样做:

$(*,$(div))。最好不要只是 div 添加一个ID或其他东西,以便父匹配很快。

Also, if you are wondering about the find method instead of adding to selector, since selectors are matched from right not from left, it may be better to separate the selector. I could also do this:
$("*", $("div")). Preferably though instead of just div add an ID or something to it so that parent match is quick.

在评论你会发现它并不快。这虽然适用于非常简单的文档,但我相信,创建jQuery对象的成本高于搜索所有DOM元素的成本。在实际的页面大小中,情况并非如此。

In the comments you'll find a proof that it's not faster. This applies to very simple documents though I believe, where the cost of creating a jQuery object is higher than the cost of searching all DOM elements. In realistic page sizes though this will not be the case.

更新:

我也非常喜欢Teifi的回答。您可以在一个地方完成,然后在任何地方重复使用它。例如,让我混淆他的方式:

I also really like Teifi's answer. You can do it in one place and then reuse it everywhere. For example, let me mix my way with his:

// In some shared libraries location:
$.extend($.expr[':'], {
    x : function(e) {
            return /^x\-/i.test(this.nodeName);
    }
});

// Then you can use it like:
$(function(){
    // One way
    var results = $("div").find(":x");

    // But even nicer, you can mix with other selectors
    //    Say you want to get <a> tags directly inside x-* tags inside <section>
    var anchors = $("section :x > a");

    // Another example to show the power, say using a class name with it:
    var highlightedResults = $(":x.highlight");
    // Note I made the CSS class right most to be matched first for speed
});

性能相同,但API更方便。

It's the same performance hit, but more convenient API.

这篇关于选择以“x-”开头的标签在jQuery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆