对INPUT和SELECT框进行Attachevent

时间:2012-10-16 18:27:11

标签: javascript html dom javascript-events

我似乎无法想象如何将事件(动态)附加到文本框和选择框:

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

2 个答案:

答案 0 :(得分:0)

为什么不使用jquery并使用bind函数:例如:

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

答案 1 :(得分:-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>