1

我想使用 Jquery 将元素动态添加到现有 div。这是HTML:

<div id="color_div" style="min-width: 100px; min-height: 60px; float: left; background: #fff;"></div>
<a href="javascript:void(0)" onclick="add_div()" >
Add new Element
</a>

这是添加新元素的 Jquery 函数

add_div = function(){
    var new_color_div = '<div style="width: 140px;"><input type="text" name="color_name[]" class="product_color_input" /></div>';
    $('#color_div').append(new_color_div);
}

现在我想在输入时更改输入背景

$(document).ready(function(){
        $('.product_color_input').each(function(){
            $(this).keyup(function(){
                var code = $(this).val();
                if (code.length==6){
                    $(this).css('background','#'+code);
                }else{
                    $(this).css('background','#ffffff');
                }
            });
        });
    });

但它不起作用。它无法识别附加到“color_div”div 的任何新元素。

为什么?

4

2 回答 2

3

由于您正在处理动态添加的元素,因此您需要使用事件委托

$(document).on('keyup', '.product_color_input', function () {
    var code = $(this).val();
    if (code.length == 6) {
        $(this).css('background', '#' + code);
    } else {
        $(this).css('background', '#ffffff');
    }
});

另外作为旁注
没有必要使用.each()循环来注册 keyup 事件处理程序,您可以利用 jQuery 提供的链接属性,框架将遍历选择器集的每个元素并将处理程序注册到每个其中。所以你不必自己迭代

$(document).ready(function () {
    $('.product_color_input').keyup(function () {
        var code = $(this).val();
        if (code.length == 6) {
            $(this).css('background', '#' + code);
        } else {
            $(this).css('background', '#ffffff');
        }
    });
});
于 2013-11-05T05:28:02.170 回答
2

尝试这样的事情,使用 id (color_div) 而不是使用文档。它会更快

        $(document).ready(function(){
            $('#color_div').on('keyup', '.product_color_input', function () {
                var code = $(this).val();
                if (code.length == 6) {
                    $(this).css('background', '#' + code);
                } else {
                    $(this).css('background', '#ffffff');
                }
            });
        });
于 2013-11-05T05:32:33.130 回答