2012-10-16 27 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')'獲取文檔中的所有選擇元素 –