为什么document.ready在点击事件后触发

时间:2013-06-07 14:12:34

标签: jquery

我为我的主页创建了一个基本幻灯片。

正确加载文档后,单击我的标记以触发click事件。它运行正常但随后文档加载运行并将所有内容重置回到开头。

它可能很明显,但我看不出问题。这是代码:

function forwardClick(){
    var Links = loadLinks();
    imgNumber = currentImgNumber();
    //now calculate the next Id
    imgNumber = Math.min(Links.length - 1, imgNumber + 1);
    nextSlider(imgNumber, Links);
}

function nextSlider(imgNumber, Links){

    //set the link for current slide
    populateLinkAndImage(Links, imgNumber);

    //replace the text of the hidden field with the current imgNum
    $('#counter').html(imgNumber.toString());
}

function populateLinkAndImage(Links, imgNumber){
    //now replace the existing image and text with the correct ones for the current imgNumber
    $("#imgHolder").attr("src", Links[imgNumber]["imgLink"]);
    $("#linkHolder").attr("href", Links[imgNumber]["aLink"]);
    $("#linkHolder").html(Links[imgNumber]["text"]);
}

function loadLinks(){
    var Links = [];
    var link0 = { imgLink: "Images/L/ipad.jpg", text: "Use our In Depth Guide to create a super profitable Hair and Beauty Salon", aLink: "P/Managing/Running-The-Perfect-Hair-Salon.aspx" };
    var link1 = { imgLink: "Images/L/ipad-sample-2.jpg", text: "Starting, buying or planning a new Cafe, build a rock solid plan here", aLink: "P/Managing/CafePlanner.aspx" };
    Links.push(link0);
    Links.push(link1);

    return Links;
}

function currentImgNumber(){
    //first find id number of current image loaded
    //could use hidden field or loop through the array to find its index
    //using hidden field
    imgText = $("#counter").html();
    imgNumber = parseInt(imgText, 10);
    return imgNumber;
}

$(document).ready(function () {

    var Links = loadLinks();

    //set the link for current slide
    populateLinkAndImage(Links, 0, "");

    //set the user interaction events
    $(".next").click(function () {
        forwardClick();
    });

});

感谢您寻找

1 个答案:

答案 0 :(得分:5)

您必须阻止链接标记的默认行为:

$(".next").click(function (e) {
        e.preventDefault();
        forwardClick();
    });