简体   繁体   中英

Trigger a click event with Jquery

I've got a ul with let's say 10 li elements. Inside every li elemenet there is img that on click is opened in modal. I want to make a function that when you send someone a link to specific img (let say www.aaa.com/#/image/3) to open the third image. So far I don't have any success. On the list I've got: $(document).on('click', 'li img', function(){ ... } Here is the question how to simulate specific img click event, cuz I've made this modal to work with this , it's not very specific like number 3 from the url.

ps I don't want to use server side, that's why I'm using #.

You can use document.location.hash to get the current hash from the link, and if there is a hash, and it's an image - trigger the click on that image:

 $(function() { // on page load var hash = document.location.hash; if (hash) { // check if hash exists m = hash.match(/#\\/image\\/(\\d+)/) // check the structure if (m) { $('ul#specific-ul li img').eq(m[1] - 1).click() // trigger click on the relevant image } } }) 

要触发点击事件,可以使用$('#image3').trigger('click')

Use the ID attribute. if you have added your li in a loop thn take a variable append it with id in loop. don't forget to do variable++.

When you will click on the image like with id = image5 you can use this $("#image5").click(function(){ // Do something });

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