将setTimeout的时间设置为0,告诉浏览器当它为当前任何挂起的事件运行完事件句柄并且完成了文档当前状态的更新后,就调用该函数,于是可用下面的例子来看效果:
<script>
function createinput(){
???????? var input = document.createElement('input');
???
???????? input.setAttribute('type', 'text');
???
???????? input.setAttribute('value', 'test1');
???
???????? document.getElementById('inpwrapper').appendChild(input);
???
???????? input.focus();
???
???????? input.select();
??? }
function createinput1(){
???????? var input = document.createElement('input');
???
???????? input.setAttribute('type', 'text');
???
???????? input.setAttribute('value', 'test1');
???
???????? document.getElementById('inpwrapper').appendChild(input);
???
???? setTimeout(function(){
????? input.focus();
????? input.select();
???? }, 0);
??? }
</script>
<form name="navbar">
? <button id="makeinput" onmousedown="createinput()" create input</button>
? <p id="inpwrapper"></p>
</form>
?由于js执行是单线程的,当执行完鼠标按下的事件处理函数后会丢掉事件句柄链,所以用createinput函数不会使新创建的text聚焦,然而使用setTimeout方法后会告诉浏览器尽快执行它所指定的函数,所以用createinput1函数会使新创建的text聚焦。
?
问题1:但是当使用的是onmouseup="createinput()" 或者onclick="createinput()" 时,并不需要用setTimeout就可以让浏览器直接调用input.focus(); input.select();这又该如何解释呢??
问题2:当在onmousedown中调用createinput()前先调用alert()事件时,input.focus(); input.select();这两个方法会被浏览器调用,然而,如果该按钮同时注册了onmouseup或onclick的话是不会被触发的(在onmouseup和onclick中调用alert也一样,因为alert会阻止了事件传递,即后续调用事件丢失)
?
?
?