0

我似乎不知道如何将事件(动态)附加到文本框和选择框:

错误:需要对象,第 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>
4

2 回答 2

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');
}); 

您可以使用 jquery 将此代码放在 onload 或 onready 函数中,如下所示:

$(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
于 2012-10-16T18:41:00.367 回答
-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>
于 2012-10-16T18:44:47.970 回答