为什么我的JavaScript代码不起作用?

时间:2011-10-25 22:12:56

标签: javascript jquery syntax-error

我不断使用此代码获取“语法错误:意外标识符”JS错误:

function hashStuff() {
    var messageID = window.location.hash.replace('#inbox-', '');
    var msgSubject = $('#subject_' + messageID).html();
    setTimeout("readMessage2(" + messageID + ", " + msgSubject + ");", 300);
}
if (window.location.hash) {
    setTimeout("hashStuff();", 400);
}

我也试过了:

if (window.location.hash) {
    function hashStuff() {
    var messageID = window.location.hash.replace('#inbox-', '');
    var msgSubject = $('#subject_' + messageID).html();
    setTimeout("readMessage2(" + messageID + ", " + msgSubject + ");", 300);
}
    setTimeout("hashStuff();", 400);
}

它们都不起作用。

我想要做的是从元素中获取信息,但我想页面还没有加载,所以我需要它在一秒后触发。我把它放在一个函数中,所以我可以使用超时,它将无法正常工作。

有什么想法吗?提前致谢。

3 个答案:

答案 0 :(得分:4)

如果您的messageID类似于1234且msgSubject是Hello World,那么正在评估的语句是:

readMessage2(1234, Hello World);

显然,这是错误的和引起错误的。

正确的代码是:

setTimeout( function() {readMessage2(messageID,msgSubject);}, 300);

答案 1 :(得分:2)

您可以在$(document).ready(function() {//script here});中运行脚本。这将确保它在所有元素加载后运行。

答案 2 :(得分:0)

尝试将代码包装在ready块中:

$(document).ready(function () {
    //your code
});