Google chrome, infinite loops and selecting text

前端 未结 2 518
醉酒成梦
醉酒成梦 2021-01-15 11:59

This question comes with a bit of background. Please see two other questions I\'ve recently posted that relate:

How to select text in a textbox cross-browser
I

2条回答
  •  萌比男神i
    2021-01-15 12:54

    Put any additional work in the setTimeout function. And add a clearTimeout() before you setTimeout():

    var focusTimeout = 0;
    $('input[type="text"]').live('focus', function(event) {
        var inp = this;
        clearTimeout(focusTimeout);
        focusTimeout = setTimeout(function() {
            $('#message-container').html($('#message-container').html() + "*\u200b");
            inp.select();
        }, 1);
    });
    

    http://jsfiddle.net/XppG9/19/

    In Chrome, writing the html to the page is (apparantly) causing the field to lose focus, and select() is causing it to receive focus 1ms later, thus triggering the focus event and causing the infinite loop. Moving the write html call into the function that selects the text seems to do the trick.

提交回复
热议问题