1

我需要将按键事件绑定到动态构建的元素形式,见下文

<div class="Customer">
<select name="dropdown1" id="dropdown1">
</select>
<input type="textbox" name="firstname1" id="firstname1">
<input type="textbox" name="lastname1" id="lastname1">
</div>

<div class="Customer">
<select name="dropdown2" id="dropdown2">
</select>
<input type="textbox" name="firstname2" id="firstname2">
<input type="textbox" name="lastname2" id="lastname2">
</div>

... and repeat..

我需要检查,只要上述任何元素发生更改,其他元素都不会为空。

表单中还有其他几个元素,尽管我只关心代码段中突出显示的这些元素。

非常感谢,

我试过下面的代码

$('.Customer').each(function (index) {

    alert("test");  // alerts the correct number of customer rows

    $("input:textbox").click(function() {
        alert("");
    })

});

解决方案应该适用于 jQuery 1.3.2

4

4 回答 4

1

看到它在这里工作

<input type="checkbox" id="test" name="test" disabled="disabled">

<div class="Customer">
<select name="dropdown1" id="dropdown1">
    <option value="1.1">1.1</option>
    <option value="1.2">1.2</option>
</select>
<input type="text" name="firstname1" id="firstname1">
<input type="text" name="lastname1" id="lastname1">
</div>

<div class="Customer">
<select name="dropdown2" id="dropdown2">
    <option value="2.1">2.1</option>
    <option value="2.2">2.2</option>
</select>
<input type="text" name="firstname2" id="firstname2">
<input type="text" name="lastname2" id="lastname2">
</div>​

$('.Customer input, .Customer select').bind("change keyup", function(){
     var me = $(this);
     var clicked = me.attr("name");
     var empty = false;
     $('.Customer input,select').each(function(){
         var elem = $(this);
             if (elem.val() == "") {
                 empty = true;
             }
     });
     if (empty) {
        $('#test').attr('disabled','disabled')
     } else {
        $('#test').removeAttr('disabled')
     }
});​

PS:输入中没有类型文本。是文字。为了在某​​些更改时触发回调,您使用“更改”而不是“点击”事件。如果您希望它同时在输入和下拉菜单上工作,则需要“输入,选择”

于 2012-06-07T19:35:40.307 回答
1

如果您想在每个文本输入上附加事件处理程序,您应该这样做

HTML(类型是“文本”而不​​是“文本框”)

<div class="Customer">
<select name="dropdown1" id="dropdown1">
</select>
<input type="text" name="firstname1" id="firstname1">
<input type="text" name="lastname1" id="lastname1">
</div>

<div class="Customer">
<select name="dropdown2" id="dropdown2">
</select>
<input type="text" name="firstname2" id="firstname2">
<input type="text" name="lastname2" id="lastname2">
</div>

js

$('.Customer').each(function (index) {
        $("input:text", this).click(function() {
        alert("");
    })

});​

​http://jsfiddle.net/pSFj3/

编辑 - 我想指出您使用了错误的语法,但正如许多人指出的那样,有更好的方法来处理事件。例如,您可以使用事件委托

$('.Customer').on( 'click', 'input:text', function() {
   alert('clicked on input');
});
于 2012-06-07T19:36:00.650 回答
1

如果您想将单击事件附加到“客户”类元素中的每个文本框,这不应该工作:

$(".Customer input[type=text]").click(function() { });
于 2012-06-07T19:36:39.493 回答
0

如果表单是在客户端上动态构建的,您将需要使用该$.on()函数。

$(document).on('keypress', '.Customer input[type="text"]', function() { ... }); 
于 2012-06-07T19:38:23.583 回答