简体   繁体   中英

How to ensure that the first slide is loaded when the page loads jQuery?

I am wondering how I can make sure the slide loads when the page is opened using this code $('#nav li a').eq(0).click(); I altered the code however it will not run or just load the first image from the slide after I click on the #1. I need it to load the first image when the page is loaded. I thank you all in advance for your help in understanding this.

    <script>

var slideArray = [
"ansel_adams1.jpg",
"ansel_adams2.jpg",
"ansel_adams3.jpg",
"ansel_adams4.jpg",
"ansel_adams5.jpg"
];

$(document).ready(function(){
var slideArray =["ansel_adams1.jpg","ansel_adams2.jpg","ansel_adams3.jpg","ansel_adams4.jpg","ansel_adams5.jpg"];

$('.container').after('<div class="slide-image"></div>');
$('.slide-image').html('<img src="images/'+slideArray[0]+'"/>');
$('.slide-image').after('<ul id="nav"></ul>');
var slideLength = slideArray.length;

for(i=0; i < slideLength; i++){
    var slideText = i + 1;
    $('#nav').append('<li><a href="#" rel="'+slideText+'">'+slideText+'</a></li>');
}


$('#nav li a').bind('click', function(){
    var numSlide = $(this).attr('rel');
    $('.slide-image').html('<img src="images/ansel_adams'+numSlide+'.jpg"/>');
    $('.slide-image img').fadeIn(2000);
    $('#nav li a').removeClass('active');
    $(this).addClass('active');

}); 
});
</script>
<body>
    <div class="container">
      <h1>Working with jQuery Events and Effects Project<//h1>
    </div>   
  </body>
</html>

I'm not 100% sure what you are wanting but if I had to guess I'd say you can simply use .trigger() to fire the click event on any element that has a click bound to it.

$('#nav li a').bind('click', function(){
    var numSlide = $(this).attr('rel');
    $('.slide-image').html('<img src="images/ansel_adams'+numSlide+'.jpg"/>');

    // added the complete callback to toggle classes when animation is finished
    $('.slide-image img').fadeIn(2000, function() {
        $('#nav li a').removeClass('active');
        $(this).addClass('active');
    });

}); 

$('#nav li a').eq(0).trigger('click');

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