【问题标题】:After Ajax Refresh, Elements are not working properlyAjax 刷新后,元素无法正常工作
【发布时间】:2017-01-21 21:08:40
【问题描述】:

在Ajax用新数据刷新div标签后,

在这里,我尝试使用以下代码获取单选按钮 [选中] 的值。

HTML 之前:

<div id="summery">

</div>

jQuery 块 1:

       $.ajax({
                url: site_addr + '/new_row_rec',
                type: 'POST',
                success: function (res) {
                    /** If error is hit, then redirect */
                    if (res.error_url) {
                        location.reload(res.error_url);
                    }
                    $('#summery').html(res);
                }
            });

HTML:

    <div id="summery">
      <input type="radio" name="payment_type[]" class="payment_type"
                                               value="A">

      <input type="radio" name="payment_type[]" class="payment_type"
                                               value="B">
    </div>

jQuery 块 2:

$('.payment_type').on('click', function () {
   var row = $('input[name="payment_type"]:checked').val();
   console.log('Row : ' + row)
 }

我得到错误:

 Row : undefined

这里首先执行jQuery Block 1并加载html内容。 之后,jQuery Block 2 通过单选按钮的点击事件运行。

我认为存在元素绑定问题,是这样吗?那有什么办法解决呢?

刷新后获取单选按钮值的任何其他方式。

注意:主页上的jQuery事件触发到新加载的页面。

【问题讨论】:

  • 请像这样完成console.log('your contents')的语法。
  • 尝试使用 on 或绑定 $(document).on('click', '.payment_type', function(){ //Here is your code });
  • 我现在修正语法!

标签: javascript jquery html ajax


【解决方案1】:

像这样更改 jQuery Block 2

$(document).on('click', '.payment_type', function () {
   var row = $('input[name="payment_type[]"]:checked').val();
   console.log('Row : ' + row);
}

您的 DOM 会因您的 AJAX 请求而更改,因此之前绑定的事件侦听器不再正确。您必须将事件侦听器绑定到文档。

【讨论】:

  • 是的,你是对的。但是这个文档级事件侦听器生成为我有多少单选按钮。
【解决方案2】:

假设 .payment_type 是从 ajax 中添加的,试试这个

 $('body').on('click','.payment_type',function () {
   var row = $('input[name^="payment_type"]:checked').val();
   console.log('Row : ' + row)
 }

【讨论】:

    【解决方案3】:

    你的inputs'名字是payment_type[],所以jQuery语句应该是:

    $('.payment_type').on('click', function () {
       var row = $('input[name="payment_type[]"]:checked').val();
       console.log('Row : ' + row)
    });
    

    结果:

    【讨论】:

    • 但这并没有解决他的问题,即在 ajax 请求之后,事件侦听器不再工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多