单击包含容器的复选框-JQuery

时间:2018-10-09 19:01:29

标签: javascript jquery

我在需要标签,复选框和容器的网站上都具有一个下拉菜单,这些菜单都可以单击以激活复选框(并更新元素的标签。

我使用过e.stopPropogation,e.stopImmediatePropagation和e.preventDefault(通常一起使用Default和stopPropagation。)

我当前的代码如下。它可以在台式机(和Chrome中的响应式台式机)上正常工作;但不适用于iOS。有什么想法吗?

  // Get the filter label.
  var label = $('#edit-f-wrapper .edit-areas-link').data('filter-label');

  // Element used to hold the label.
  var title = $('#edit-f-wrapper .edit-areas-link label');

  // Get a list with all checkboxes.
  var checkboxes = $('#edit-f-wrapper input:checkbox');

  // Click triggers
  var clickTrigger = $('.form-type-bef-checkbox');

  // Determine click action to take depending on browser/device
  var action = ('ontouchend' in window) ? 'touchend' : 'click';

  var checkBoxID = 'input[id^="edit-f-rc-core-cat-evrn-svgeographic"';

  // Act on checkbox click - check if action is set, if not, set it to default click
  clickTrigger.one(action, function (e) {

    e.stopImmediatePropagation();

    // Get child of clicked element
    var checkboxChild = $(this).children("input[type=checkbox]").eq(0);

    // Check it if the checkbox itself wasn't clicked
    checkboxChild.prop('checked', !checkboxChild.prop('checked')).change();

  }).on(action, checkBoxID, function(e) {
    e.stopImmediatePropagation();
    e.preventDefault();

    // Check it if the checkbox itself wasn't clicked
    $(this).prop('checked', !$(this).prop('checked')).change();

  }).on(action, "label", function(e) {
    e.stopImmediatePropagation();
    e.preventDefault();

    var checkboxChild = $(this).parent().children("input[type=checkbox]").eq(0);
    // Check it if the checkbox itself wasn't clicked
    checkboxChild.prop('checked', !checkboxChild.prop('checked')).change();

  });

  // When we have a change of state...
  $(checkBoxID).on('change', function() {
    console.log("Changed!");

    // Update the title to reflect how many items have been checked.
    var items = [];

    checkboxes.each(function () {
      var checkbox = $(this);

      if (checkbox.prop('checked')) {
        items.push(checkbox.next('label').html());
      }
    })

    // Update the label data.
    if (!items.length) {
      title.html(label);
    }
    else if (items.length === 1) {
      title.html(label + ': ' + items[0]);
    }
    else {
      title.html(label + ': ' + items.length + ' selected');
    }
  });

并且,HTML标记:

<div class="form-item form-type-bef-checkbox form-item-edit-f-rc-core- 
cat-evrn-svgeographicarch-cape"> 

    <input type="checkbox" name="f[]" id="edit-f-rc-core-cat-evrn-svgeographicarch-cape" value="rc_core_cat_evrn_svgeographic:Arch Cape">

    <label class="option" for="edit-f-rc-core-cat-evrn-svgeographicarch-cape">Arch Cape</label> 

</div>

0 个答案:

没有答案