How does a fire work? first element

I have this simple script

html code

<div id='div1'> <ul> <li><a href='#gone'>gone</a></li> <li><a href='#gtwo'>gtwo</a></li> </ul> </div> <div id='div2'> <ul> <li><a href='#g1'>g1</a></li> <li><a href='#g2'>g2</a></li> </ul> </div> 

js code

 init(); function init(){ target = $('#div1').find('ul'); target.on('click','a',function(){ alert ($(this).attr('href')); }); target.trigger('click'); } 

How does a fire work? first element to be with href #gone

+4
source share
2 answers

You can assign a unique identifier to each anchor tag and use it as

 <div id='div1'> <ul> <li><a href='#gone' id='gone' >gone</a></li> <li><a href='#gtwo' id='gtwo'>gtwo</a></li> </ul> </div> 

And there will be javascript.

 $("#gone").trigger("click"); 

And it would be very simple

 $("#gone").bind("click",function(event){ //your code. }); 

If your ul li is dynamic, you can use like:

 $('#div1 ul li').first().find("a").trigger("click"); 
+6
source

I would use first-child ( DEMO ):

 init(); function init(){ target = $('#div1 ul'); target.on('click','a',function(){ alert ($(this).attr('href')); }); $('li:first-child a', target).trigger('click'); } 
+1
source

Source: https://habr.com/ru/post/1482730/


All Articles