在 GWT 中通过 CSS 选择器查找元素 [英] Find an element by CSS selector in GWT

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

问题描述

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

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

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

有人在 GWT 中使用过通用 CSS 选择器吗?

解决方案

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

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

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

I'm trying to grab an arbitrary element using a CSS selector (eg. "#someId .className a") in GWT.

I'm building a JS widget that can live on a 3rd party website and want to be able to interact with elements on the page. Searching through the JavaDocs I don't see anything that can find an element by selector. I did come across GQuery, but it seems like the project might be dead and I'm not sure if it works with GWT 2.

One option I've considered is wrapping an existing library (jQuery, Mootools, Prototype, etc) into a GWT class and exposing the desired behavior through JSNI. It seems this might be very builky.

Anyone have experience using generic CSS selectors in GWT?

解决方案

There's the DOM class, that provides many wrapper methods for accessing the DOM tree. There's no function that takes a CSS selector jQuery style that I'm aware of - GWT just encourages/enforces accessing DOM elements through Widgets (and such), not directly - though I understand that in your case such "low-level" approach might be needed. The only way I see pulling that off through pure Java GWT methods is via lots and lots of (probably horrible) chaining/invocations of the DOM class. It'd be easier if all you had to do was access some id - for that there's RootPanel.get(id) (and DOM.getElementById(id), they differ in what type of objects they return).

However, like you already suggested, JSNI might offer a better solution - try returning, for example, $wnd.$("#someId .className a") from JSNI as an Element - actually, you can return anything as anything from JSNI, GWT will just crap up the second you try to use, say an int as a DOM element or something.

PS: while the GQuery project does seem dead/inactive, it might be worth checking how they wrapped the jQuery calls (such as $) so that they could be used seemingly in GWT.

这篇关于在 GWT 中通过 CSS 选择器查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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