2012-10-16 28 views
0

我似乎无法如何计算,以了解如何安装一个事件(动态),以文本框和选择框:的attachEvent输入和选择框

错误:所需的对象,行19

<!DOCTYPE html> 
<html> 

    <head> 
     <script type="text/javascript"> 
      window.onload = function fnOnLoad() { 
       var t = document.getElementsByTagName('SELECT'); 

       var i; 
       for (i = 0; i < t.length; i++) { 
        alert(t[i].id) 

        document.getElementById(t[i].id).attachEvent('onfocus', function() { 
         document.getElementById(this.id).style.backgroundColor = "#FFFF80" 
        }) 
        document.getElementById(t[i].id).attachEvent('onblur', function() { 
         document.getElementById(this.id).style.backgroundColor = "#FFFFFF" 
        }) 

       } 
      } 
     </script> 
    </head> 

    <body> 
     <input id="t1" type="text"> 
     <input id="t2" type="text"> 
     <input id="t3" type="text"> 
     <br> 
     <br> 
     <select id="d1"></select> 
     <select id="d2"></select> 
     <select id="d3"></select> 
    </body> 

</html> 
+0

您在IE中测试它? – dfsq

+1

您需要在DOM准备就绪时执行此操作,而不是在onload事件中执行此操作。 –

+0

看看这个:http://stackoverflow.com/q/3474037/405117 – Vikram

回答

-1
<script type="text/javascript"> 

function fnOnLoad() { 

    var t = document.getElementsByTagName('INPUT'); 
    for (var i = 0; i < t.length; i++) { 
      t[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';}; 
      t[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; }; 
    } 

    var d = document.getElementsByTagName('SELECT'); 
    for (var i = 0; i < d.length; i++) { 
      d[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; }; 
      d[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; }; 
    } 

} 
</script> 
0

你为什么不使用jQuery和使用绑定功能:例如:

var element = $('#myElementId') // equivalent to document.getElementById 
element.bind('click', function() { 
    // when the element is clicked, it will do what ever you write here 
    alert('i was clicked'); 
}); 

你可以把这个代码在onload或onready函数中使用jQuery这样的:

$(function() { 
    var element = $('#myElementId') // equivalent to document.getElementById 
    element.bind('click', function() { 
     // when the element is clicked, it will do what ever you write here 
     alert('i was clicked'); 
    }); 
}); // this is the onload 

$(document).ready(function() { 
    var element = $('#myElementId') // equivalent to document.getElementById 
    element.bind('click', function() { 
     // when the element is clicked, it will do what ever you write here 
     alert('i was clicked'); 
    }); 
}); // this is the on ready 
+0

顺便说一句 - 你可以绑定所有的选择元素,让他们与jquery选择器,而不是'$('#myElementId')'你会使用'$('select')'获取文档中的所有选择元素 –