jquery-the first one to click will bound on all the items

谁说我不能喝 提交于 2019-12-06 13:29:22

I think the problem lies with the following lines:

var swatchesName = $('input[name=optradio]:checked').val();
--
$('.swatches').html(html);
--
$('input[name=optradio]').change(function() {
  populateswatches();
});

These don't just target the elements in the active modal window, but all elements that match the provided selectors. So that goes beyond the scope of the active modal window and includes all other modal windows as well.

$('.swatches').html(html); will change the HTML of all elements with a classname of swatches, not just the span in the active modal window. This explains why you're seeing the results of the first item with the other items as well.
Then when you try to change the option you run into a problem with var swatchesName = $('input[name=optradio]:checked').val(); because this one will always return the value of the radio button that you checked with the first item.

To solve this you can pass the element that was clicked on to the populateswatches function. In this function you can then look for the parent modal to which this element belongs. For any other elements that you then want to target, you only look for elements that are below this modal.

function populateswatches($el) {
  var $modal = $el.closest('.modal');
  var swatchesName = $el.val();
  $.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) {
    var html = '';
    $.each(swatch, function(index, array) {
      html = html + 
             '<div class="col-md-3 w3-margin-top">' +
               '<div class="w3-display-container w3-hover-opacity">' +
                 '<div class="w3-center">' +
                   '<input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required>' +
                 '</div>' +
                 '<div class="w3-display-middle w3-display-hover">' +
                   '<a href="../backend/functions/images/'+array['images']+'" target="_blank">' +
                     '<button type="button" class="btn btn-primary">' +
                       '<i class="fa fa-search fa-lg" aria-hidden="true"></i>' +
                     '</button>' +
                   '</a>' +
                 '</div>' +
                 '<img src="../backend/functions/images/'+array['images']+'" style="width:100%">' +
                 '<div class="w3-center">' + array['swatches_code']+'</div>' +
               '</div>' +
             '</div>';
    });
    $modal.find('.swatches').html(html);
  });
}

$(function() {
  $('input[name=optradio]').on('click', function() {
    populateswatches($(this));
  });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!