JQuery 复选框筛选器参数

JQuery checkbox filter parameter

本文关键字:参数 筛选 复选框 JQuery      更新时间:2023-09-26

我有流派过滤器的复选框列表。这是 HTML

<div class="gl-title">Türler</div>
<ul class="check-list filters" id="genres">
  <?php foreach($genres as $genre){?>
    <li>
      <div class="customCheck">
        <input type="checkbox" data-genrename="<?php echo $genre->slug; ?>" id="tur_<?php echo $genre->term_id;?>">
        <label for="tur_<?php echo $genre->term_id;?>"></label>
      </div>
      <div class="cl-text">
        <?php echo $genre->name;?>
      </div>
    </li>
    <?php }?>
</ul>
</div>

在复选框上单击我想在 url 的末尾添加流派名称。这是我的JQuery代码

$(".customCheck").children("input").unbind(click).click(function(){
    if ($(this).is(":checked")) {
        $(this).prop("checked", false);
    } else {
        $(this).prop("checked", true);
    }
    alert("blabla");
    var curUrl = window.location.href;
    alert(curUrl);
    if(curUrl.substring("?tur=")>-1){
        window.location=curUrl+"+"+$(this).attr("data-genrename");
    }else{
        window.location=curUrl+"?tur="+$(this).attr("data-genrename");
    }
});

"tur"在我的语言中的意思是流派。(因为你可以理解网址。此功能处于文档就绪状态。检查功能正常工作,但我在单击时看不到警报框。我尝试使用隐身模式进行缓存,没有任何变化。什么是问题

非常感谢

每当你想玩复选框时,请始终使用 .change() 事件而不是 .click()。

您可以使用 Ctrl + 空格键选中或取消选中复选框,此时不会触发 .click() 事件。

 $(document).on("change", ".customCheck :checkbox", function() {
    if ($(this).is(":checked")) {
        $(this).prop("checked", false);
    }
    else {
        $(this).prop("checked", true);
    }
    alert("blabla");
    var curUrl = window.location.href;
    alert(curUrl);
    if (curUrl.substring("?tur=") > -1) {
        window.location = curUrl + "+" + $(this).attr("data-genrename");
    }
    else {
        window.location = curUrl + "?tur=" + $(this).attr("data-genrename");
    }
});

这可以简单得多,修复一些语法问题和子字符串被滥用的问题,应该改用str.indexOf(searchValue[, fromIndex])

注意 我在这里使用.data.attr作为更好的方法。 !$(this).is(":checked")也可以!$(this)[0]checked甚至!this.checked

编辑:通过删除类来调整绑定问题

$('#genres').on("change", "input[type='checkbox']", function() {
  // set checkbox to what it is NOT (checked or unchecked (not sure why)
  $(this).prop("checked", !$(this).is(":checked"));
  alert("blabla");
  var curUrl = window.location.href;
  alert(curUrl);
  var turp = "?tur=";
  if (curUrl.indexOf(turp) > -1) {
    window.location = curUrl + "+" + $(this).data("genrename");
  } else {
    window.location = curUrl + turp + $(this).data("genrename");
  }
});

请注意,你也可以这样做:(但哪个更好是有争议的)

var curUrl =  (window.location.href.indexOf(turp) > -1) window.location.href + '+': window.location.href+"?tur=";
window.location = curUrl + $(this).data("genrename");