当我点击复选框动态 url
创建时。如果我刷新页面而不是复选框显示选中如果品牌名称有一些值(value)我的 javascript
代码工作正常。
Shop?brand=Emporio,Primigi%2088&category=&gender=&start=2000&end=4000
问题是如果品牌名称包含像 primigi 88 这样的空格,Lee Cooper 会选择所有复选框。我只想选中 url 中的复选框。
$(function() {
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL =
decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var brand = getUrlParameter('brand');
if (brand) {
var brand_array = brand.split(",");
for (var i = 0; i < brand_array.length; i++) {
$('input[type=checkbox][value=' + brand_array[i] +
']').attr('checked', true); // this will working fine if categories name not contain any space
}
}
var category = getUrlParameter('category');
if (category) {
var category_array = category.split(",");
for (var i = 0; i < category_array.length; i++) {
$('input[type=checkbox][value=' + category_array[i] +
']').attr('checked', true);
}
}
var gender = getUrlParameter('gender');
if (gender) {
var gender_array = gender.split(",");
for (var j = 0; j < gender_array.length; j++) {
$('input[type=checkbox][value=' + gender_array[j] +
']').attr('checked', true);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group">
<h3>Brands</h3>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="North East">North East</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Emporio">Emporio</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Lee Cooper">Lee Cooper</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Primigi 88">Primigi 88</a>
<a href="#" class="list-group-item">
<input type="checkbox" class="item_filter brand" value="Us polo assn">Us polo assn</a>
</div>
最佳答案
问题是因为您需要将属性选择器中的值用引号引起来,以便也包括空格,例如:
$('input[type="checkbox"][value="' + gender_array[j] + '"]')
也就是说,您可以做一些事情来改进您的逻辑。首先,尽可能使用 prop()
而不是 attr()
。其次,将函数声明为变量时不需要函数名。
最后,您还可以通过构建一个包含所有过滤器的大型数组并循环遍历该数组来删除检查复选框的重复 block ,从而使逻辑变干。试试这个:
$(function() {
var getUrlParameter = function(sParam) {
// param retrieval logic...
};
var brands = (getUrlParameter('brand') || '').split(',');
var categories = (getUrlParameter('category') || '').split(',');
var genders = (getUrlParameter('gender') || '').split(',');
var filters = brands.concat(categories).concat(genders);
filters.forEach(function(filter) {
$(`input[type="checkbox"][value="${filter}"]`).prop('checked', true);
});
});
关于javascript - 从 url 获取值而不是使用 javascript 选择复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50622511/