2011-09-11 39 views
3

我正在动态创建一个表并想要捕获动态创建日期文本框上的按键事件。如果我只有一个payment_date文本框,那很好,但我有很多。我已经看过.live,但我太新了,以此弄清楚。有人可以为我特定吗?这里是有问题的文本框的HTML:关于动态创建文本框的jQuery按键事件

 <?php 
     foreach($student_classes as $class): 
      if($student['student_id'] == $class['student_id']) {     
       $i = $class['registration_id']; 
       $deleted = FALSE; 
     ?> 
      <td> 
       <input type="text" 
       name="students[<?php echo $i ?>][registration_payment_date]" 
       id="payment_date[<?php echo $i ?>]" 
       value="<?= html($class['registration_payment_date']) ?>" 
       size='10' maxlength="10" 
       > 
      </td> 
     <?php endforeach; ?> 

的jQuery:

jQuery(document).ready(function() 
{ 
     var $payment_date = jQuery('#payment_date');  
     // Format the date as it is entered 
      $payment_date.keypress(function(event) { 
      DateFormat(this, this.value, event, false, '1'); 
     }); 

    // Check to make sure the date is valid 
     $payment_date.change(function() 
    { 
     if(dateValid(this.value) == false); 
     alert('The date is not valid'); 
    }); 
}); 

谢谢!

回答

0

使用jQuery.live()它添加功能元素选择哪些werearewill be在DOM结构

http://api.jquery.com/live/

var $payment_date = jQuery('#payment_date');  
    // Format the date as it is entered 
    $payment_date.live("keypress",function(event) { 
     DateFormat(this, this.value, event, false, '1'); 
    }); 

// Check to make sure the date is valid 
    $payment_date.live("change",function() 
{ 
    if(dateValid(this.value) == false); 
    alert('The date is not valid'); 
}); 
+0

谢谢。我过于复杂 - 它使用起来非常简单。我会再读一遍,以便我能理解它。 – Sara

4

虽然jQuery.live()会的工作,最好不要接近JavaScript开发这种方式。

发出<input>元素时,添加“payment_date”作为一个类。现在,说

$(".payment_date").bind("keypress", function(event){ 
    DateFormat(this, this.value, event, false, '1'); 
} 

这样做的好处是,它将适用于任何数量的具有payment_date类的div。

+0

你的解决方案很好,我应该考虑使用一个类。我很好奇为什么你建议不使用jQuery.live()? – Sara

+0

如果您使用与该查询相匹配的live,_any_元素,甚至在未来处理该回调时创建。 假设有一个很大的代码库,有人做了jQuery.live('。foo'),你不知道这一点,并动态地用class =“foo”创建一个元素。现在,如果你使用jQuery.bind,它可以正常工作。如果你不这样做,它也会执行前面的回调。 这是我的原因,还有其他原因 - http://stackoverflow.com/questions/1368223/performance-difference-between-jquerys-liveclick-fn-and-clickfn/1368310#1368310 – antileet2

0

JQuery live()方法现在已弃用,并已从1.9中移除。

您应该使用on()方法将事件绑定到动态创建的元素。