javascript函数在完成后重新加载页面

时间:2016-02-20 18:01:13

标签: javascript jquery html reload

我有一个简单的javascript程序,可以单击图像。

但是,每当我点击图片时,页面都会重新加载。

经过大量调试后,我发现在脚本完成之前页面没有重新加载。

代码中有几个setTimeouts,但我注意到页面正在立即重新加载。我甚至将这些超时时间更改为15000毫秒,但它仍然会立即重新加载。

我正在使用jquery,如果它有任何区别。

每次单击它时,我也希望程序得到不同的结果,这样每次单击它时都会运行不同的脚本,并且某些文本会按特定顺序更改。我通过将每个脚本中的图像的onclick属性更改为下一个脚本的名称来完成此操作,以便脚本1可以切换到脚本2,依此类推。我在这些开关上设置了超时,这样一次点击就不会遍历每个脚本。脚本二没有运行,所以很有效。

我的代码:

function getSounds() {
    console.log("script. initiated");
    $("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
    console.log("new message");
    $("#soundwebGetSoundA").attr('href',"");
    console.log("href eliminated");
    setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000); 
    console.log("onclick to findFile()");

}

function findFile(){
    console.log("FINDFILE")
    $("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below.  Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end.  Once you have all that stuff typed, click the icon again.");
    console.log("FIND IT, DARN IT!!");
    $("#soundwebGetSoundPathInput").css("opacity",1);
    console.log("diving into reader");
    setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000); 
}
function readFile(){
    console.log("loading...");
    $("#soundwebGetSoundDirections").html("loading...");
    if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
        setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
        setTimeout(findFile(),2000);
    }

}

和链接到的HTML,

<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
                    <img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
                </a>

感谢您的帮助, Lucas N。

2 个答案:

答案 0 :(得分:0)

您没有正确使用setTimeout。你应该传递一个函数而不是一个声明。所以,例如,而不是

setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);

你应该使用

setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);

我认为设置onclick属性同样如此,但我从未尝试动态更改onclick属性。

由于您已经在使用jQuery,因此如果您当前的设置不起作用,可以尝试使用.on('click'....off('click'...

答案 1 :(得分:0)

如果您不想单击图像以使锚标记加载href,则将图像标记移动到锚标记之外。