1

我有这段代码-完美运行

$('.canti,.precio').change(function() {
 var total = 0;
 var $item = $(this).parent();
 var canti = $item.find(".canti").val();
 var precio = $item.find(".precio").val();  
 total = parseFloat(canti * precio); 
 $item.find(".subto").attr("value", total); 
});

它根据字段集进行计算

<fieldset class="item">
<input name="item[]" type"text" value="" />
<input class="canti" name="cantidad[]" type"text" value="" />
<input class="precio" name="preciounitario[]" type"text" value="" />
<input class="subto" name="importe[]" type"text"value="" readonly="readonly"/>
</fieldset> 

我有多个实际的字段集,并且效果很好。然而,我希望用户能够根据需要添加,而不是最初有 X 字段集,所以这样写:

var newFieldset='<fieldset class="item"><input name="item[]" type"text" value="" /><input class="canti" name="cantidad[]" type"text"  value="" /><input class="precio" name="preciounitario[]" type"text"  value="" /><input class="subto" name="importe[]" type"text"value="" readonly="readonly"/></fieldset>'
$(".add").click(function(){
    $(".add").before(newFieldset);
});

再次 - 完美地工作并添加了一个新的字段集但是在新的“虚拟”字段集中对 .canti 和 .precio 项目的计算没有做任何事情。

有任何想法吗?我希望做的甚至可能吗?

在http://www.cristalyaluminiodiestro.com/estimate-create-testing有一个更完整的版本

4

2 回答 2

2

需要委托事件

您可以使用 jQuery.on()方法

$('body').on('change','.canti,.precio' ,function() {

这是因为您添加事件的方式不适用于动态创建的元素

'body' 可以替换为最近的静态父容器。

于 2012-12-15T00:06:25.633 回答
2

是的,这是可能的,您只需要将事件处理程序附加到作为所有祖先的元素,这可以使用以下on方法

$('body').on('change', '.canti,.precio', function() { ... });

之所以如此,是因为更改处理程序仅附加到'.canti,.precio'在 DOM 就绪时通过过滤器的元素 - 您动态添加的元素显然不会存在,因此不会附加处理程序。

在上面的示例中,我使用 body 元素作为所有元素的共同祖先,如果您能够这样做,最好使用更接近的共同祖先来实现性能共振。

于 2012-12-15T00:07:15.257 回答