使用xpath在jQuery中选择元素? [英] using xpath to select elements in jQuery?

查看:108
本文介绍了使用xpath在jQuery中选择元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有允许我执行此操作的插件?它说在此处( XPath兼容性插件)中删除了该功能jQuery 1.2版及其链接的插件不见了!

Is there a plugin to allow me to do this? It says here (XPath Compatibility Plugin) that the functionality was removed back in Jquery version 1.2 and the plugin it links is gone!

推荐答案

大多数浏览器支持 document.evaluate() 用于选择带有XPath表达式的元素-无需jQuery.唯一缺少支持的主要浏览器是Internet Explorer. Dimitri Glazkov已创建了一个库,该库将实现IE缺少的功能,但是.

Most browsers support document.evaluate() for selecting elements with XPath expressions - no jQuery required. The only major browser lacking support is Internet Explorer. Dimitri Glazkov has created a library that will implement the missing functionality for IE, however.

var result = document.evaluate("//a[@href='#']", document, null, 0, null),
    item;

while (item = result.iterateNext()) {
    // item will be an <a> element with href="#" here
}

您也可以轻松创建一个插件来包装此功能:

You could easily create a plugin to wrap this functionality too:

(function($) {
    $.xpath = function(exp, ctxt) {
        var item, coll = [],
            result = document.evaluate(exp, ctxt || document, null, 5, null);

        while (item = result.iterateNext())
            coll.push(item);

        return $(coll);
    }
})(jQuery);

// And call it like so:
$.xpath("//a[@href='#']").click(function () { return false; });

这篇关于使用xpath在jQuery中选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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