gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:18:27 25 4
gpt4 key购买 nike

看来

$(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com