首页 > 解决方案 > Jquery 不将类标识为选择器

问题描述

我有两个 Jquery 函数,其中一个将在单击按钮时将新的动态行插入到表单中,而其他函数将验证该行中的单元格。

var currentItem = 11;
$('#addnew').click(function(){
  currentItem++;
  $('#items').val(currentItem);
  var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control"  name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button  class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';

  $('#data').append(strToAdd);


});

这里我将类名productSelect作为第二个函数的标识符进行验证。但它无法识别该类,并且验证不适用于我通过上述函数添加到表单中的行。

  $('.productSelect').change(function () {

  var elementID = $(this).attr("id");
  var numberPart = elementID.split("t", 2);

  if ($(this).val() != null ) {
    $('#quantity'+ numberPart[1]).prop('required',true);
  }
});

这就是整个代码的样子

<script type='text/javascript'>

$(document).ready(function() {

$('.productSelect').change(function () {

  var elementID = $(this).attr("id");
  var numberPart = elementID.split("t", 2);

  if ($(this).val() != null ) {
    $('#quantity'+ numberPart[1]).prop('required',true);
  }
});

var currentItem = 11;
$('#addnew').click(function(){
  currentItem++;
  $('#items').val(currentItem);
  var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control"  name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button  class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>';

  $('#data').append(strToAdd);


});

});

</script>

标签: javascriptjqueryformsvalidation

解决方案


使用 $(document).on.('change', '.productSelect', function (){}) 因为方法找不到文档准备好的类


推荐阅读