How can I use nth-child to modify the child element style after getting the child element?

rt.

<div id="searchProgram">
    <div class="program"></div>
    <div class="program"></div>
    <div class="program"></div>
</div>


   $(".program").click(function(){
                    var channelIndex = $(this).index();
                    $("-sharpsearchProgram").children().css({"display":"none"});
                    $("-sharpsearchProgram div:nth-child(channelIndex)").css({"display":"block"});
                });

this cannot modify the style of the child div. Error:

clipboard.png

resolved, the last line is changed to:

$("-sharpsearchProgram div:nth-child("+channelIndex+")").css({"display":"block"});
                    });

Jul.14,2021

$("div > div:last"). Index ()


. Index ()

< hr >


  1. notice that these two are not the same thing (take a closer look at the coloring of the code). The one below is just a string, not a variable. This should at least be written as $("- sharpsearchProgram div:nth-child (" + channelIndex + ")") (without discussing advanced syntax).
  2. .css ("display", "block") and .css ("display", "none") are not recommended. It is generally recommended to have an extra tool class in the stylesheet, such as .hide {display:none;} , and then drive it with .addClass ("hide") and .removeClass ("hide") . In addition, there are a pair of .hide () and .show () in jQ, and .toggle () , which are characterized by a wide range of applications, because the front style driver is only suitable for display:block elements (or elements of a single display), and these three API are widely applicable to any element because jQ automatically caches their display values.
  3. this can only be suggested, take a look at the jQ document in the" selector "and" traversal "two pieces of API, multi-purpose filter, want to practice more. Be careful when using a single API more than twice (such as .children (). Children (). Children () ), which means that noodles will be made out of noodles if there is something wrong with the taste in the code.
  4. I don't know if that's what you mean:

    $("-sharpsearchProgram").on("click", ".program", function(){
      $(".program").hide();
      $(this).show();
    });

    anyway, I didn't use .index () .

Menu