jQuery 如何为表单的所有输入绑定事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8999207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:23:15  来源:igfitidea点击:

How to bind an event for all inputs of form?

jqueryformsinput

提问by skywind

I have a form with inputs (with id's). And i need to bind one event to click on any input in this form.

我有一个带有输入的表单(带有 ID)。我需要绑定一个事件来点击这个表单中的任何输入。

Now, I use this construction:

现在,我使用这种结构:

    $("#siteAdress").click(function(){
        $("#reg-login").click();
    });
    $("#phoneNumber").click(function(){
        $("#reg-login").click();
    });
    $("#reg-email").click(function(){
        $("#reg-login").click();
    });
    $("#reg-login").click(function(){
        // DO SOMETHING
    });

How to optimize it?

如何优化它?

回答by zneak

The easiest way is probably to add a class to all the elements you need to bind on, and use it:

最简单的方法可能是为您需要绑定的所有元素添加一个类,然后使用它:

$(".event-user").click(function() { /* do something */ })

If this is not an option, you can use an idfor your form, and query all its input children:

如果这不是一个选项,您可以id为您的表单使用 an ,并查询其所有输入子项:

$("#my-form input[type=text]").click(function() { /* do something */ })

And if neither is possible, you can always use a comma-separated list of selectors:

如果两者都不可能,您始终可以使用逗号分隔的选择器列表:

$("#siteAddress, #phoneNumber, #reg-email, #reg-login")
    .click(function() { /* do something */})

回答by Chris Kempen

Depending on the types of inputs you have, you could do it broadly or fine grain it. For example, if they're all inputtype elements, just do it broadly:

根据您拥有的输入类型,您可以广泛地或细粒度地进行。例如,如果它们都是input类型元素,那么就广泛使用:

$('input').click(function(){ ... });

Otherwise, if you want to do it specifically for text input types, for example, you can do this:

否则,例如,如果您想专门针对文本输入类型执行此操作,则可以执行以下操作:

$('input[type="text"]').click(function(){ ... });

It's all in the selectors! Hope this helps...

这一切都在选择器中!希望这可以帮助...

回答by sathishkumar

Use this

用这个

$("form input:text").click(function(){
  $("#reg-login").click();
});

回答by Rehan Khan

   $('form input').click(function (e) {
            SearchForm();//Call function you want
            return false; 
        });

   $('form input').keypress(function (e) {
            SearchForm();//Call function you want
            return false; 
   });

回答by nihilis

You should use the general > sign. Meaning you can get the form id and then with one line append the click function to all children:

您应该使用一般 > 符号。这意味着您可以获取表单 ID,然后用一行将 click 函数附加到所有子项:

$('#formId > input').each(function () {
    $(this).click(function () {
        //SOME CODE - btw you can ge the value with this.value;
    })
});

hope this helps.

希望这可以帮助。