【问题标题】:On change event doesn't work with dynamically created item更改事件不适用于动态创建的项目
【发布时间】:2017-03-30 20:57:23
【问题描述】:

更改事件

$('.amount').on('change','input', function(){
        alert('hello!');
});

动态创建的项目:

<tr id="row{{$data['product_id']}}">
    <td><input type="checkbox" name="product[]" value="{{$data['product_id']}}"></td>
    <td>{{$data['product_id']}}</td>
    <td class="amount">{!! Form::input('number','qty',$data['qty'],['id'=>$data['product_id'],'min'=>'1','max'=>\App\Product::find($data['product_id'])->quantity,'required'=>'required'])!!}
    </td>
    <td>{{$data['stock']}}</td>
    <td id="rowprice{{$data['product_id']}}">{{$data['price']}} $</td>
    <td id="rowsum{{$data['product_id']}}">{{$data['qty']*$data['price']}} $</td>
</tr>

添加此项目:

$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

        var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: $('#editOrderContent').attr('action'),
            data: data,
            success: function (html) {

               if (html.success) {
                    $('#summary').before(html.tdProduct);
                }
            }
        });

    });

因此,当我尝试使用新创建的项目更改 qty 输入的值时,事件不会触发,但当我重新加载页面时,它会触发。

【问题讨论】:

  • uhhh no :C 试过 $('.amount').on('change',$( ":input" ), function(){ },还尝试了阻止默认值,仍然没有' t 工作(((

标签: javascript jquery ajax


【解决方案1】:

当您绑定到一个类、ID 等时,jQuery 只能绑定到页面上当前的元素。它看不到未来。对此的常见解决方法是绑定到文档。很难看出你真正想绑定什么,但这里有一个例子。

$(document).on('change','.amount input', function(){
        alert('hello!');
});

【讨论】:

  • 我想把它绑定到一个 td 里面有一个类数量和一个输入
猜你喜欢
  • 2012-07-02
  • 2019-08-04
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2014-01-16
  • 2013-07-20
相关资源
最近更新 更多