有没有办法根据 jQuery 中的 DOM 元素生成 CSS 选择器
有没有办法获取 DOM 对象并推断出可用于稍后查找该元素的 CSS 选择器。
示例:
<ul class="items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script type="text/javascript">
var second = $('.items li:eq(1)');
console.log(get_css_selector(second));
</script>
其中 get_css_selector
将返回类似于 .items li:eq(1)
的内容,或者至少返回一个可用于选择元素的字符串。
如果有一种方法可以基于以下内容生成 CSS 选择器,那就太好了:
<script type="text/javascript">
var third = document.getElementsByTagName('li')[2];
console.log(get_css_selector(third));
</script>
Is there a way to take a DOM object and infer a CSS selector that could be used to find that element at a later time.
Example:
<ul class="items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script type="text/javascript">
var second = $('.items li:eq(1)');
console.log(get_css_selector(second));
</script>
Where the get_css_selector
would return something similar to .items li:eq(1)
or at least a string that would work to select the element.
Bonus would be if there was a method to generate a CSS selector based on:
<script type="text/javascript">
var third = document.getElementsByTagName('li')[2];
console.log(get_css_selector(third));
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您正在尝试使用原始选择器。我的说法正确吗?还是我把事情过于简单化了?
原始选择器存储在您创建的 jQuery 对象中。
尝试一下: http://jsfiddle.net/9JUJL/
或者奖金,这个? http://jsfiddle.net/9JUJL/2/
It appears as though you're trying to use the original selector. Am I right about that? Or have I over-simplified things?
The original selector is stored in the jQuery object you created.
Try it: http://jsfiddle.net/9JUJL/
Or for the bonus, this? http://jsfiddle.net/9JUJL/2/