简体   繁体   中英

How to select the nth child of an element and assign a click() function?

I'm receiving an index number (for the sake of the example var index). I have a some 'li'. I need to assign the click() function to the 'li' that is located on the index position. ie If I have index = 1, I need to get the first 'li' clicked.

I tried many things but most of them give me error. Any approach is OK as long as I can assign click() to the li that has the same number as the value in index.

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>

    <ul class="product-gallery-dots product-dots">
        <li aria-hidden="true" role="presentation" aria-selected="true" aria-controls="navigation10" id="slick-slide10">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">1</button>
        </li>
        <li aria-hidden="true" role="presentation" aria-selected="false" aria-controls="navigation11" id="slick-slide11" class="">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">2</button>
        </li>
        <li aria-hidden="true" role="presentation" aria-selected="false" aria-controls="navigation12" id="slick-slide12" class="">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">3</button>
        </li>
    </ul>


    <ul class="product-gallery-dots product-dots">
        <li aria-hidden="true" role="presentation" aria-selected="true" aria-controls="navigation20" id="slick-slide20">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">1</button>
        </li>
        <li aria-hidden="true" role="presentation" aria-selected="false" aria-controls="navigation21" id="slick-slide21" class="">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">2</button>
        </li>
        <li aria-hidden="true" role="presentation" aria-selected="false" aria-controls="navigation22" id="slick-slide22" class="">
            <button type="button" data-role="none" role="button" aria-required="false" tabindex="0">3</button>
        </li>
    </ul>

<script>

var ul = document.getElementsByClassName('product-gallery-dots product-dots');
var index = 2; //could be any other number
ul[0].children().eq(index).click(); //ERROR

</script>
</body>
</html>

I think that the problem also has to do with the fact that the var 'ul' in this case is a HTMLUListElement when I apply a[0] and for that reason, I can't assign events.

you can only call jQuery methods on jQuery objects - at the moment you have done your selection using vanilla JS, and so ul is a JS object not a jQuery one. Either replace var ul = document.getElementsByClassName('product-gallery-dots product-dots'); with var ul = $(".product-gallery-dots.product-dots").get(0) and keep the rest of the code the same, or you could try

$(".product-gallery-dots.product-dots").eq(0).children().eq(index).click()
  1. Pass in an arbitrary list of numbers (the rest operator ( ... ) will treat list of numbers as an array):

     // positions = 2, 5, 9, 44, 0, 7 function clickButton(...positions) {...
  2. Target the button within each list item:

     $('li button')
  3. Collect all of them into a jQuery collection then convert that into an array:

     const buttons = $('li button').toArray();
  4. In each iteration of a for...of loop get the current [index, button] by destructuring each entry returned by buttons.entries() ...

     for (let [index, button] of buttons.entries()) {...
  5. ...if a number from the parameters ( ...positions ) matches an index number +1 ....

     if (positions.includes(index + 1)) {...
  6. ...click the current button programmatically.

     button.click();
  7. For demonstration purposes a click handler has been registered to each button to show which buttons were clicked.

    In most collections like array, NodeList, jQuery collection, etc. they have a 0-index which means there's an offset of -1 of a normal count. You should really get in that mindset of counting collections starting from 0 if you plan on programming more in the future.

     function clickButton(...positions) { const buttons = $('li button').toArray(); for (let [index, button] of buttons.entries()) { if (positions.includes(index + 1)) { button.click(); } } } $('li button').on('click', function(e) { $(this).toggleClass('on off'); }); clickButton(0, 2, 5, 7, 8, 10, 15);
     ul { display: inline-block; list-style: none } button { display: block; width: 5ch; cursor: pointer } .on { color: #fff; background: #000 }
     <ul> <li><button class='off'>1</button></li> <li><button class='off'>2</button></li> <li><button class='off'>3</button></li> <li><button class='off'>4</button></li> <li><button class='off'>5</button></li> </ul> <ul> <li><button class='off'>6</button></li> <li><button class='off'>7</button></li> <li><button class='off'>8</button></li> <li><button class='off'>9</button></li> <li><button class='off'>10</button></li> </ul> <ul> <li><button class='off'>11</button></li> <li><button class='off'>12</button></li> <li><button class='off'>13</button></li> <li><button class='off'>14</button></li> <li><button class='off'>15</button></li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM