使用 jquery 向动态生成的元素添加 keyup 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18487097/
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-26 21:45:17  来源:igfitidea点击:

Adding keyup events to dynamically generated elements using jquery

javascriptjquery

提问by Ansuman

I have a button which creates text boxes dynamically and there is another button 'Clear'.

我有一个动态创建文本框的按钮,还有另一个按钮“清除”。

If there is no text in any of the text field then the clear button is disabled or else it will be enabled. It works for the text box that is created when the dom is loaded but for the dynamically created textboxes it does not work.

如果任何文本字段中都没有文本,则清除按钮将被禁用,否则它将被启用。它适用于加载 dom 时创建的文本框,但对于动态创建的文本框不起作用。

Here is the HTML

这是HTML

<input type="button" value="Click Me" class="a" />
<input type="button" value="Clear" class="a" id="clearBasicSearch" />
<div id="basicSearchFields">
    <input type="text" />
</div>

Javascript

Javascript

$(".a").click(function () {
    $("#basicSearchFields").append("<input type='text' class='b' />");
});

/*$(".b").live("keyup", function () {
        //alert('you pressed ' + $(this).val());
        $(this).val($(this).val().toUpperCase());
        });*/

var toValidate = $("#basicSearchFields input[type='text']");
$("#clearBasicSearch").removeClass('hidden').removeClass('button').attr('disabled', true);

toValidate.live('keyup', function () {
    console.log("hi");
    var valid = false; //default is false
    toValidate.each(function () {
        if ($(this).val().length > 0) {
            valid = true; //non-empty element found
            return false; //break
        }
    });
    $("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});

JSfiddle link - http://jsfiddle.net/TpExS/

JSfiddle 链接 - http://jsfiddle.net/TpExS/

Please help me out!!

请帮帮我!!

回答by Okky

Try this

尝试这个

$(document).on('keyup', "#basicSearchFields input[type='text']",function () {
    console.log("hi");
    var valid = false; //default is false
    var toValidate = $("#basicSearchFields input[type='text']");
    toValidate.each(function () {
        if ($(this).val().length > 0) {
            valid = true; //non-empty element found
            return false; //break
        }
    });
    $("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});

回答by Arun P Johny

Try

尝试

$("#basicSearchFields").delegate("input[type='text']", 'keyup', function () {
    validate();
});

function validate(){
    console.log("hi");
    var valid = false; //default is false
    var toValidate = $("#basicSearchFields input[type='text']");
    toValidate.each(function () {
        if ($(this).val().length > 0) {
            valid = true; //non-empty element found
            return false; //break
        }
    });
    $("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
}

Demo: Fiddle

演示:小提琴

回答by Dart

Here is another possible solution http://jsfiddle.net/TpExS/2/

这是另一个可能的解决方案http://jsfiddle.net/TpExS/2/

Note: JQuery 2.0.2 used

注意:使用 JQuery 2.0.2

Javascript

Javascript

$(document).ready(function(){
    var fields = $('input[class=b]');
    for(var i = 0; i < fields.length; i++){
        $(fields[i]).on('keyup', validateFields);
    }
});

$(".a").click(function () {
    var newField = $('<input/>').attr('type', 'text').attr('class', 'b');
    $(newField).on('keyup', validateFields);

    $("#basicSearchFields").append(newField);
});

function validateFields(){
    if($(this).val().length){
        $('#clearBasicSearch').attr('disabled', false);
        return;
    }

    $('#clearBasicSearch').attr('disabled', true);
    var fields = $('input[class=b]');
    for(var i = 0; i < fields.length; i++){
        if($(fields[i]).val().length){
            $('#clearBasicSearch').attr('disabled', false);
            return;
        }
    }
}

回答by Roger Barreto

Simple, Updates your global "toValidate" variable when you add more elementson the click.

简单,当您在单击时添加更多元素时更新您的全局“toValidate”变量。

$(".a").click(function () {
    $("#basicSearchFields").append("<input type='text' class='b' />");
    toValidate = $("#basicSearchFields input:text");
});

Why? The time you set toValidate, it will return an array at that moment, you should updates it in each time there are new elements, or check for all of then inside the live event.

为什么?当你设置为Validate时,它会在那一刻返回一个数组,你应该在每次有新元素时更新它,或者在实时事件中检查所有 then 。

回答by Shirish Dhotre

$(document).on('keyup', "input#basicSearchFields",function () {  
    // do something here
}