我有流派过滤器的复选框列表。这是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的末尾添加genrename.Here是我的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”表示我的语言类型。(因为你可以理解网址。) 此功能在文档准备就绪。检查功能正常,但我无法在点击时看到警告框。我尝试使用隐身模式进行缓存,没有任何改变。什么是问题非常感谢
答案 0 :(得分:2)
每当您想要使用复选框时,请始终使用.change()事件而不是.click()。
您可以在此时使用Ctrl + SpaceBar键选中或取消选中复选框。不会触发.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");
}
});
答案 1 :(得分:1)
这可以更加简单,修复一些语法问题以及子字符串被滥用的问题,而应该使用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");