15

我正在尝试使用 GWT 中的 CSS 选择器(例如“#someId .className a”)来获取任意元素。

我正在构建一个 JS 小部件,它可以存在于 3rd 方网站上,并且希望能够与页面上的元素进行交互。搜索 JavaDocs 我看不到任何可以通过选择器找到元素的东西。我确实遇到了 GQuery,但似乎该项目可能已经死了,我不确定它是否适用于 GWT 2。

我考虑过的一种选择是将现有库(jQuery、Mootools、Prototype 等)包装到 GWT 类中,并通过 JSNI 公开所需的行为。看起来这可能非常笨重。

有人有在 GWT 中使用通用 CSS 选择器的经验吗?

4

5 回答 5

8

有一个DOM类,它提供了许多用于访问 DOM 树的包装方法。我知道没有采用 CSS 选择器 jQuery 样式的函数 - GWT 只是鼓励/强制通过小部件(等等)而不是直接访问 DOM 元素 - 尽管我知道在你的情况下这种“低级”方法可能被需要。我看到通过纯 Java GWT 方法实现这一目标的唯一方法是通过大量(可能是可怕的)DOM类的链接/调用。如果您所要做的就是访问一些会更容易id- 因为那里有RootPanel.get(id)(而且DOM.getElementById(id),它们返回的对象类型不同)。

但是,就像您已经建议的那样,JSNI 可能会提供更好的解决方案 - 例如,尝试$wnd.$("#someId .className a")从 JSNI 作为Element返回 - 实际上,您可以从 JSNI 返回任何内容,GWT 只会在您尝试使用的第二次使用时报废,比如说int 作为 DOM 元素或其他东西。

PS:虽然 GQuery 项目看起来确实已死/不活动,但可能值得检查它们如何包装 jQuery 调用(例如$),以便它们可以在 GWT 中使用。

于 2010-03-09T01:40:00.210 回答
6

使用 GwtQuery,更新到 GWT 2.4:http ://code.google.com/p/gwtquery/

选择器示例:

//select an element having id equals to 'container'
GQuery myElement = $("#container");
//select all elements having 'article' as css class
GQuery allArticles = $(".article");
/select all cells of tables
GQuery allCells = $("table > tr > td");
//find the ul elements being inside a element with class 'article' itself inside a element with id 'container'
GQuery articleUls = $("#container .article ul");

http://code.google.com/p/gwtquery/wiki/GettingStarted

于 2012-07-28T05:50:33.363 回答
3

您可以使用可用于较新浏览器的 querySelector() 和 querySelectorAll()...

http://www.javascriptkit.com/dhtmltutors/css_selectors_api.shtml

...在浏览器支持方面,Firefox 3.1+、IE8+(仅在 IE8 标准模式下)和 Safari 3.1+ 支持 querySelector() 和 querySelectorAll()

于 2010-07-02T10:31:09.537 回答
3

灵感来自Asfand Yar Qazi 的回答

使用JSNI,您只需定义此方法并在您的 Web 应用程序在现代浏览器中运行时享受它。

public final native NodeList<Element> querySelectorAll(String selectors) /*-{
 return $doc.querySelectorAll(selectors);
 }-*/;
于 2015-06-19T21:25:08.420 回答
1

这是一个使用 GWT Element 和 Node 类来查找具有给定类名的单个嵌套元素的示例。这不像文字 CSS 选择器那样开放和强大,但可以根据您的特定用例的需要进行修改:

static public Element findFirstChildElementByClassName( Widget w, String className ){
    return findFirstChildElementByClassName( w.getElement(), className );
}
static private Element findFirstChildElementByClassName( Element e, String className ){     
    for( int i=0; i != e.getChildCount(); ++i ){
        Node childNode = e.getChild(i);
        if( childNode.getNodeType() == Node.ELEMENT_NODE ){
            Element childElement = (Element)childNode;
            if( childElement.getClassName().equalsIgnoreCase( className ) )
                return childElement;
            else if( childElement.hasChildNodes() ){
                Element grandChildElement = 
                    findFirstChildElementByClassName( 
                            childElement, className );
                if( grandChildElement != null ) return grandChildElement;
            }
        }
    }
    return null;
}
于 2016-05-05T18:48:24.960 回答