简体   繁体   中英

Javascript stops working after this code

I have written this code for a cmd console-like typing effect. The code itself works fine but any code I place after it doesn't work. I've been trying to figure it out for a while now and I'm pretty stuck.

Here's a JSFiddle of the problem. http://jsfiddle.net/GWj4b/

/**
 * CONSOLE
 */

setInterval(cursorBlink, 500);
function cursorBlink() {
    if($('#cursor').css('visibility') == 'hidden'){
        $('#cursor').css({'visibility': 'visible'});
    } else {
        $('#cursor').css({'visibility': 'hidden'});
    }
}

var text = $('#type').html();
var text = text.replace(/<br>/g, '_');

$('#type').html('');

$.each(text.split(''), function(i, letter) {
    setTimeout(function(){
        if(letter == '_'){
            $('#type').html($('#type').html() + '<br />');
        } else {
            $('#type').html($('#type').html() + letter);
        }
    }, 100 * i);
});

You're not using HTML right?

after

$('#type') returns undefined , and then you do text.replace(/<br>/g, '_');

you cannot do undefined.replace , so it fails, and the execution stops.

Try to add the html code for that JS code

Also, you must add JQuery to your fiddle, in the Frameworks & Extensions part.

See this fiddle http://jsfiddle.net/9748L/

If you look in the console log you see: Uncaught TypeError: Cannot call method 'replace' of undefined

text is not defined when you call replace on it because the element you're looking for doesn't exist.

You can test to see if it exists like this

if(text) {
  text.replace(/<br>/g, '_');
}

Javascript will stop execution if it hits a runtime error like this.

Consider learning more about debugging this type of issue with Chrome's dev tools or an equivalent in your browser. Once you look to see the error, its pretty clear what line is causing the issue.

Incidentally, after adding the elements that you are trying to reference, the code executes through. If they might not exist though, you need to do the checking in code, and its a good habit regardless.

http://jsfiddle.net/GWj4b/1/

我刚刚调试了它,看起来文本是未定义的,所以也许您还没有在html中创建该元素。

var text = text.replace(/<br>/g, '_');

Indeed you are missing some html code and the text you try to manipulate is undefined . You could add the following html code,

<span id="type">is this what you try to do????</span><span id="cursor">_</span>

to achieve the effect you are aiming for.

http://jsfiddle.net/JKp5z/

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