首页 > 解决方案 > CheckBox 事件未触发

问题描述

我正在使用一个 jquery 数据表,其中一列是一个复选框。所以在选择它时,更改事件不会触发..这是我的代码......

$("#divAddDocument").on("change", $("input[id*='addDocCheckbox_']"), function (e) {
    var checkboxId = e.target.id;
    var _index = checkboxId.substring(checkboxId.lastIndexOf('_') + 1, checkboxId.length);
    _docUpload.DmsDocumentsList[_index].IsGridItemSelected = true;
    if (_docUpload.IsCorrespondence) {
        $("input[id*='addDocCheckbox_']").each(function () {
            if (checkboxId != $(this).id) {
                $(this).prop("disabled", true);
                $(this).prop("checked", false);
                var _counter = $(this).id.substring($(this).id.lastIndexOf('_') + 1, $(this).id.length);
                _docUpload.DmsDocumentsList[_counter].IsGridItemSelected = false;
            }
        });
    }
});

-------------数据表列------

var columns = [
        {
            "data": "", "width": "25%", "name": "Add", "title": "Add", "orderable": false,
            render: function (data, type, row) {
                return '<input type="checkbox" name="Checkbox" class="addDocCheckBox" id="addDocCheckbox_' + row["Counter"] + '">'
            }
        },
        { "data": "DocumentType", "width": "25%", "name": "Document Type", "title": "Document Type", "orderable": false },
        { "data": "IndividualName", "width": "25%", "name": "Name", "title": "Name", "orderable": false },
        { "data": "UploadDateTime", "width": "25%", "name": "Upload Date/Generated", "title": "Upload Date/Generated", "orderable": false }
];

任何帮助表示赞赏..

标签: jquery

解决方案


主要问题是您需要提供一个字符串作为on()委托事件处理程序中的第二个参数,而不是您当前的 jQuery 对象。后者不起作用,因为当您尝试选择它时,DOM 中不存在该元素,因此 jQuery 对象为空。这是一个固定版本:

$("#divAddDocument").on("change", "input[id*='addDocCheckbox_']", function(e) {
  // your code...
});

另一个问题是重复使用$(this).id. id不是 jQuery 对象的属性,因此它将始终返回undefined.

要解决此问题,请使用idElement 本身的属性:

this.id

或者使用prop()通过jQuery获取属性的方法:

$(this).prop('id')

这是您的逻辑的完全更新版本:

$('#divAddDocument').on('change', 'input[id*="addDocCheckbox_"]', function(e) {
  var _index = this.id.split('_')[1];
  _docUpload.DmsDocumentsList[_index].IsGridItemSelected = true;

  if (_docUpload.IsCorrespondence) {
    $('input[id*="addDocCheckbox_"]').each(function() {
      if (checkboxId != this.id) {
        this.disabled = true;
        this.checked = false;
        var _counter = this.id.split('_')[1];
        _docUpload.DmsDocumentsList[_counter].IsGridItemSelected = false;
      }
    });
  }
});


推荐阅读