开发者

Being selective with jQuery - Selecting a specific div and image

Looking for a jQue开发者_Python百科ry ninja's assistance. My jQuery below works but I have a strong suspicion that how I have selected these elements can be much improved. How best to select these elements? Can my code be improved? (See purpose below, important to note I only want to select the first div class results and image within)

<div id="priceInventory">
<div class="Hdr">Some Unique Header</div>

<div class="results"> 
    <div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div> 
        <div style="display: none;" id="RandomId">Unique Content</div>                                                                                                          
</div>

<div class="results"> 
    <div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div> 
        <div style="display: none;" id="RandomId">Unique Content</div>                                                                                                          
</div>

<div class="results"> 
    <div onclick="showInfo('#RandomId');" class="xx yy"><img class="arrow" src="/images/arrow-up.png"> Title</div> 
        <div style="display: none;" id="RandomId">Unique Content</div>                                                                                                          
</div>
<!-- results repeats -->    

<script>
$("body div#priceInventory div:nth-child(2) div:nth-child(2)").show();
$("body div#priceInventory div:nth-child(2) div:nth-child(1) img").attr('src','/images/arrow-dwn.png');
</script>

The general purpose of the code is to display the content of only the first set of content when the page loads. The arrow is also updated to indicate the this content is being displayed.

Thanks so much, I heart you stackoverflow friends. I hope others find this helpful as well.


From the looks of it this should be a little more elegant. Just a selector reduction, but I think that is what you are looking for. This will do the same thing you are doing above, unless you have other elements outside of this heir achy that use the .results and .arrow classes.

$(".results:first div:hidden").show();
$(".results:first .arrow").attr('src','/images/arrow-dwn.png');


I personally would prefer:

<script>
$("#priceInventory .results div div.someclass").show();
$("#priceInventory .results div img.arrow").attr('src','/images/arrow-dwn.png');
</script>

Someclass is a class that you add to the 2nd nested div. I personally don't like using nth-child because it breaks when I change the order/layout.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜