更改按钮以选择代码更改
我有我的脚本工作,但目前它使用了一个按钮输入,我想将其更改为选择框输入,但我似乎无法让代码工作,请帮助
$(function() { var fuel = ''; // Keep track of selections var drive = ''; var type = ''; $('#fuel button').click(function() { // Choose a fuel fuel = (this.id ? '.' : '') + this.id; selectModels(); }); $('#drive button').click(function() { // Choose a drive drive = (this.id ? '.' : '') + this.id; selectModels(); }); $('#type button').click(function() { // Choose a colour type = (this.id ? '.' : '') + this.id; selectModels(); }); function selectModels() { // Select matching models $('div.modelContainer').hide(). // Hide all filter((fuel + drive + type) || '*').show(); // Show matches } }); fuel: drive: type: pmc pm4 pac dmc dmv dac da4 da7 sor
并将“燃料”按钮更改为
fuel: all petrol diesel
谢谢
这个问题有很多需要改进的地方,但这应该会立即给你带来结果:
$('#fuel select').on("change", function() { fuel = (this.value ? '.' : '') + this.value; selectModels(); });
您还需要为其他select
元素重复相同的操作。
更新一些更改:
这段代码存在一些问题,可能会让您在将来感到沮丧。 我冒昧地重新写了一下。 虽然可能仍有一些改进空间,但我认为它会让你更接近一些更容易处理和理解的东西。
我首先将所有可过滤标准存储在单个对象中,而不是几个变量中。 这为我们提供了一个推动和拉动价值的地方。
var fType = { 'fuel' : 'all', 'drive' : 'all', 'type' : 'all' };
接下来,我将创建一个小的正则表达式模式,该模式将在预定义的CSS选择器中查找关键字。 函数partsMapper
将负责交换正则表达式发现的关键字,其中包含上述fType
对象的实际值。
var partsRegex = /([az]+)/g; function partsMapper ( s, p ) { return fType[p]; }
接下来,我将所有select
元素分组到一个
以便我们可以更轻松地从一个地方捕获他们的更改事件。
$(".controller").on("change", "select", function(){
当select
的change事件从fType
,我们fType
在fType
对象中更新该change事件的值。 因此,如果更改了#fuel
,我们将把fType[fuel]
更新为新值。
// Set new value fType[ this.id ] = this.value;
我们的fType
对象刚刚更新,我们可以更新我们的项目列表。 我们首先隐藏所有列表项(是的,我在这里进行了重组)。 接下来,我们只选择与.fuel.drive.type
选择器匹配的列表项,其中每个关键字都被找到并被我们的正则表达式/函数组合替换为fType
对象中的当前值。
因此,如果fType.fuel
是"petrol"
,那么我们的选择器将以.petrol
。 默认情况下, "all"
条件都设置为"all"
,因此一旦将#fuel
更改为petrol
,我们的选择器将立即变为.petrol.all.all
,其中显示所有.petrol
项。
// Update filtered items $(".modelList li") .hide() .filter('.fuel.drive.type'.replace( partsRegex, partsMapper )) .show();
最后,我们关闭$.on
方法。
});
演示: http : //jsbin.com/imezez/edit#javascript,html