This question already has answers here:
Event binding on dynamically created elements?
                            
                                (23个答案)
                            
                    
                去年关闭。
        

    

我正在做这个演示。在将某些复选框动态添加到隐藏内容(如引导程序模态)时,如何获取$(this)或什至checked元素的值?



$('#exampleModal').on('show.bs.modal', function(e) {

  for (var i = 0; i < 3; i++) {
    $('.modal-body').append('<input type="radio" name="addOD" value="item' + i + '" />');
  }
})

$('input:radio[name=addOD]').on('click', function() {
  console.log($(this).val());
  var val = $('input:radio[name=lenseopttype]:checked').val();
  console.log(val);
});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

最佳答案

如果输入是动态添加的,则将单击处理程序更改为如下所示。

$(function () {
    $(document).on('click', 'input:radio[name=addOD]', function () {
        console.log($(this).val());
        var val = $('input:radio[name=lenseopttype]:checked').val();
        console.log(val);
    });
});


This post将有助于进一步解释

关于javascript - 如何将动态添加的复选框的此值转换为隐藏内容? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55301818/

10-10 01:58