0

我对 JavaScript 和 jQuery 比较陌生。我正在尝试一些适用于图像点击事件的图像滑块代码。但是,我希望它在文档加载后自行运行。我怎样才能做到这一点?我试图将代码放在里面$(document).ready(),但它不起作用。这是我的代码:

<script>
var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    $("#right").click(function () {
        present_slide = "#slide" + present;
        next_slide = "#slide" + next;
        $(present_slide).css("top", "200px");
        $(next_slide).css("top", "0px");
        present++;
        next++;
        if (present == (total + 1)) {
            present = 1;
            next = 2;
            for (i = 1; i <= 4; i++) {
                $("#slide" + i).css("top", "200px");
            }
            $("#slide1").css("top", "0px");
        }
    });
});
</script>

这里 -#right是与 img 元素关联的 id。#slide1, #slide2, 等是与包含多个图像的 div 关联的 id。

4

5 回答 5

1
$(document).ready(function (){

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

});
于 2013-09-16T16:11:48.703 回答
0

删除$("#right").click(function () {或添加$('#right').trigger('click').

var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    present_slide = "#slide" + present;
    next_slide = "#slide" + next;
    $(present_slide).css("top", "200px");
    $(next_slide).css("top", "0px");
    present++;
    next++;
    if (present == (total + 1)) {
        present = 1;
        next = 2;
        for (i = 1; i <= 4; i++) {
            $("#slide" + i).css("top", "200px");
        }
        $("#slide1").css("top", "0px");
    }
});

或者

var total = 4;
var present = 1;
var next = 2;
$(document).ready(function () {
    $("#right").click(function () {
        present_slide = "#slide" + present;
        next_slide = "#slide" + next;
        $(present_slide).css("top", "200px");
        $(next_slide).css("top", "0px");
        present++;
        next++;
        if (present == (total + 1)) {
            present = 1;
            next = 2;
            for (i = 1; i <= 4; i++) {
                $("#slide" + i).css("top", "200px");
            }
            $("#slide1").css("top", "0px");
        }
    }).trigger('click');
});
于 2013-09-16T16:12:19.107 回答
0

尝试替换$(document).ready()$(window).onload = function(){ ... }

于 2013-09-16T16:07:58.857 回答
0

当窗口加载时,您可以手动触发图像的“单击”事件

$(window).load(function() {
  $("#right").trigger('click');
}

一旦加载了所有资源,这将触发点击。

于 2013-09-16T16:14:21.090 回答
-1

在脚本块的底部,放置以下行:

$("#right").trigger('click');
于 2013-09-16T16:04:39.970 回答