jQuery:绑定keydown,除了一个之外的相同行为

时间:2009-09-19 17:21:21

标签: jquery validation binding keydown

我有一些输入(文本类型)。除了一个之外,我想对所有人采取同样的行为。

我试过了:

$(document).ready(function() {

    $("input[type=text]").bind('keydown', function(e) {
        ....
    });

    $("#MyOtherInput").keydown(function(e) {
        .....
    });

});

MyOtherInput是具有特定行为的输入类型texte ....

你能帮帮我吗?

谢谢,

3 个答案:

答案 0 :(得分:1)

试试这个:

$('input[type=text]').not('input[type=text]#MyOtherInput').bind('keydown', function(e)
{
    ............
});

除了myotherinput control之外,它将选择带有文本类型的所有输入。请尝试以下示例。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<body>
    <div id="testdiv">
        <input id="Text1" type="text" /><br />
        <input id="Text2" type="text" /><br />
        <input id="Text3" type="text" /><br />
        <input id="Text4" type="text" /><br />
        <input id="Text5" type="text" /><br />
        <input id="Text6" type="text" /><br />
        <input id="MyOtherInput" type="text" />
    </div>
</body>

<script type="text/javascript">

    $(function()
    {
        $('input[type=text]').not('input[type=text]#MyOtherInput').bind('keydown', function(e)
        {
            alert('Common for all ');
        });

        $('input[type=text]#MyOtherInput').bind('keydown', function(e)
        {
            alert('Only for MyOtherInput');
        });        

    });

</script>

</html>

答案 1 :(得分:0)

只需在需要特定事件的字段上解除绑定事件。

$("#MyOtherInput").unbind("keydown").keydown(function(){});

答案 2 :(得分:0)

您可以使用类名来获取输入框,然后使用它

$(document).ready(function() {

    $(".InutClass").bind('keydown', function(e) {
        ....
    });

});

上面的代码将绑定所有具有InputClass的元素,输入字段的css类。