简体   繁体   中英

Why is my JavaScript code not working?

I keep getting the "Syntax Error: Unexpected identifier" JS error with this code:

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);
}

I've also tried:

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);
}

Neither of them work.

What I was trying to do was get information from the elements but I guess the page wasn't loaded yet so I need it to trigger after a second. I put it in a function so I can use a timeout and it will not work.

Any ideas? Thanks in advance.

If your messageID is something like 1234 and the msgSubject is Hello World, then the statement being evaluated is:

readMessage2(1234, Hello World);

Which, clearly, is incorrect and error-inducing.

The correct code is:

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

You can run the script inside $(document).ready(function() {//script here}); . That will make sure that it is run after all the elements have loaded.

try wrapping your code inside ready block:

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

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