2010-07-06 91 views
1

我有一个大致有这个结构的大HTML文档:jQuery选择帮助

<div id="a"> 
    <!-- more html code here --> 
    <span id="title">...</span> 
    <!-- more html code here --> 
</div> 
<div id="b"> 
    <!-- more html code here --> 
    <span id="title">...</span> 
    <!-- more html code here --> 
</div> 
... 
... 
<div id="z"> 
    <!-- more html code here --> 
    <span id="title">...</span> 
    <!-- more html code here --> 
</div>  

注意外的DIV的ID为这是唯一的( “A”, “B”,...,“Z “),但内部SPAN具有非唯一的标识(”标题“)。

要选择一个SPAN这是DIV“Q”里,比如,我尝试使用这样的:

$("#q").find("#title"); 

这跑得快于FF和Chrome,但find()方法需要较长的时间来在IE8(和IE7)中执行。有没有其他方法可以做到这一点?

请让我知道,如果我可以提供任何进一步的信息。

+8

对我的作品* “但内部SPAN具有非唯一的ID”*这是无效的,ID必须是唯一的。你应该使用类来代替。 ' ...' – user113716 2010-07-06 21:58:47

回答

8

因为ID必须是唯一的,所以您应该将标记更改为使用<span>元素的类替代ID。

<div id="a"> 
    <!-- more html code here --> 
    <span class="title">...</span> 
    <!-- more html code here --> 
</div> 
<div id="b"> 
    <!-- more html code here --> 
    <span class="title">...</span> 
    <!-- more html code here --> 
</div> 
... 
... 
<div id="z"> 
    <!-- more html code here --> 
    <span class="title">...</span> 
    <!-- more html code here --> 
</div> 

则:

$("#q").find(".title"); 

如果我没有记错,即特别是与非唯一ID的麻烦。将您的代码更改为以上版本可能会为您带来诀窍。

+0

你说得对。希望是那样。但我无法控制这些ID。无论如何,感谢您的回答......看起来像我在这里被冲走。 – 2010-07-06 22:07:06

+1

如果您只有一个跨度,您可以通过$(“#q”)来完成。find(“span”) – Marko 2010-07-06 22:12:06

+0

可以有多个跨度。但根据你的建议,我可以试试$(“#q”)。find(“span#title”)。也许这会有所帮助。 – 2010-07-06 22:16:22

2

正如其他人所说,代码无效。但是,如果你坚持使用它,你应该能够做到这一点,以正确选择它。如果没有运行测试,我不知道怎么高性能,这将是在你尝试另一种方法:

$("#b span[id=title]"); 
+0

这也会起作用 – Marko 2010-07-06 22:31:51

+0

+1 - 我刚刚在我的建议下留下了一条评论(删除),提示同样的事情,然后向下滚动,看到你用长镜头击败了我! :O) – user113716 2010-07-06 22:39:12

0

如何像

$("#q").find("span").each(function() { 
    if($(this).attr("id") == "title") { 
     $(this).css('color','red'); 
    } 
}); 

这在IE/FF