切换自定义复选框时如何单击最近的锚点

时间:2012-09-14 16:36:23

标签: javascript jquery

Faceted search with Custom Checkbox

HTML

<li class="leaf">

  // The span is my custom checkbox that wraps around the default checkbox.     
  <span class="checkbox facetapi-checkbox checked">

    // The span above replaces the default checkbox below, which you'll notice has a display:none; I don't want both checkboxes showing.
    <input type="checkbox" class="facetapi-checkbox" checked="true" style="display: none; ">

  </span>


  // This is the anchor tag that I need to click when my custom checkbox is checked.
  // It's outside of my custom checkbox span, but shares the same parent.  
  <a href="/part-finder/field_rep_catalog/heater-1527" rel="nofollow" class="facetapi-active facetapi-checkbox-processed" style="display: none; ">(-) 
     <span class="element-invisible">Remove Support filter</span>
  </a>

</li>

以下是用于将默认复选框替换为自定义复选框的jQuery:

//Checkbox Image Replacement 
$('.faceted_search_column input[type=checkbox]').each(function() {
  var span = $('<span class="' + $(this).attr('type') + ' ' + $(this).attr('class') + '"></span>').click(doCheck).mousedown(doDown).mouseup(doUp);
  if ($(this).is(':checked')) {
    span.addClass('checked');
  }
  $(this).wrap(span).hide();
});

// You'll notice that when this function is run, I've attempted to use .closest() to find the nearest anchor and then do a .triggerHandler('click') to click that anchor it finds. This obviously didn't work. Should I use .parent() to move back in the DOM?
function doCheck() {
  if ($(this).hasClass('checked')) {
    // This was my attempt to click the anchor when doCheck function is run.
    $(this).closest('a.facetapi-checkbox-processed').triggerHandler('click');
    $(this).removeClass('checked');
    $(this).children().prop("checked", false);
  } else {
    $(this).parents('a.facetapi-checkbox-processed').triggerHandler('click');
    $(this).addClass('checked');
    $(this).children().prop("checked", true);
  }
}

function doDown() {
  $(this).addClass('clicked');
}

function doUp() {
  $(this).removeClass('clicked');
}

当用户切换复选框时,您有什么建议作为触发锚定点击的最有效方式?它是一个分面搜索锚,因此我需要选中或取消选中以触发相同的锚标记。

提前感谢那些花时间帮助我的人。

2 个答案:

答案 0 :(得分:1)

您需要替换以下行:

$(this).closest('a.facetapi-checkbox-processed').triggerHandler('click');

这个:

$(this).siblings('a.facetapi-checkbox-processed').triggerHandler('click');

答案 1 :(得分:1)

最近只查看元素直接祖先。你可以使用最接近('li')和find('a')的组合来实现你的目标。

 $(this).closest('li').find('a.facetapi-checkbox-processed').click();

TriggerHandler不会向dom树冒泡,所以它试图仅触发Anchor上的点击,没有绑定到Anchor标签的触发器。使用触发器(“单击”)或简单地使用.click()将事件传播到跨度上的事件处理程序,或更改查找以直接查看跨度。