jquery - 使用jquery获取解析的html结果集中元素的索引

标签 jquery

看来

$(html).find('*').index('#theID');

产量-1,而

$(html).find('*').each(function(ind){if(this.id=='theID') alert('found! @'+ind) } );

有效(警报 229)

我使用的是 Windows 7 以及 IE 8jquery 1.6.1

我的问题是,为什么第一个不起作用?谢谢。

最佳答案

查看 index 的 jQuery 文档。字符串参数的 API 如下(添加斜体强调):

selector A selector representing a jQuery collection in which to look for an element.

...

If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.

要执行您想要执行的操作,需要传递一个元素(或 jQuery 对象)作为参数,而不是字符串。因此,像这样的事情应该做你想要的:

$(html).find("*").index($("#theID", html));

编辑(参见评论)

由于 html 是一个字符串,因此从该字符串创建 2 个不同的 jQuery 对象将会导致问题。要解决这个问题,您可以将其传递到 jQuery 一次:

var $html = $(html);
$html.find("*").index($html.find("#theID"));
<小时/>

这种形式的索引的文档说明如下:

element The DOM element or first element within the jQuery object to look for.

...

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

关于jquery - 使用jquery获取解析的html结果集中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8901294/

相关文章:

javascript - 我如何为单选按钮创建类似所需警报的 HTML5?

javascript - Angular : Filter Multiple Items

javascript - Qunit 数据已删除

javascript - $ "i"+i) 中的变量 ("#show"不工作

jquery - 使用 jQuery 拉伸(stretch)图像以填充整个 div,它在窗口调整大小时调整大小

javascript - "li"行内元素的高度

javascript - $.ajax 位于 $.each 阻塞浏览器中

javascript - 在整个表上一一运行 Ajax 请求

jquery - NiceScroll Scroller 在比滚动的 div 宽度更小的 div 中

javascript - 在多个输入文件元素上添加事件监听器