简体   繁体   中英

how should i trigger a click of img tag inside a ul?

<div id="product_parts">
                    <ul id="product_list">
                      <li class="active" data-maxlength="200" > <img src="images/ts/1.jpg" /> </li>
                      <li data-maxlength="200" > <img src="images/ts/2.jpg" /> </li>
                      <li data-maxlength="60" > <img src="images/ts/3.jpg" /> </li>
                      <li data-maxlength="60" > <img src="images/ts/1.jpg" /> </li>
                    </ul>
</div>

Here is an unordered list. i have a function that runs when the img tag of a list is clicked.Now i want this myfunction() to run for every img list item. This is my funnction

$('#product_parts li>img').click(function(){
    $('#product_parts li').removeClass('active');
    $(this).parents('li').addClass('active');
    var selected_canvas_image = $(this).attr('src');

    var obj = 'main_layer_'+($(this).parents('li').index() + 1) ;

    add_canvas(false,selected_canvas_image,'','all',obj);

})

This was the solution i tried

var lis = document.getElementById("product_list").getElementsByTagName('li').find('li);
for(i=0;i<lis.length();i++)
{
lis[i].click();
}

Unfortunately it doesnt work

In your Vanilla JavaScript, there is several problems.

One, you have a syntax error: for(i=0;i<lis.length();i++)

length isn't a function, but you are using it as one. It should be lis.length instead:

for (i = 0; i < lis.length; i++) {
  lis[i].click();
}

Two, you are triggering a click event on #product_list li , not the img :

var lis = document.getElementById("product_list").getElementsByTagName('li');

You should select the img instead of the li :

var lis = document.getElementById("product_list").getElementsByTagName('img');

If you are fine with losing a little bit of browser support , you can use querySelectorAll() :

var lis = document.querySelectorAll("#product_list li>img");

Your code should now look like:

var lis = document.querySelectorAll("#product_list li>img");
for (i = 0; i < lis.length; i++) {
  lis[i].click();
}

However

You are already using jQuery in you project, so you might as well use it's functions:

$("#product_list li>img").click()

Much shorter, much easier.

Since you use Jquery already here is a simple solution

$( "#product_parts li>img" ).each( function( index, element ){
   $(element).click();
});

Just iterate over each of the image in list and click them.

Here is a working JS Fiddle.

https://jsfiddle.net/g838s4zd/2/

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