具有单个类(没有其他选择器)的从属下拉列表(链接的选择) [英] Dependent Dropdowns (Linked Selects) with single class (no other selectors)
问题描述
我正在尝试以独特的方式创建多个相关的下拉列表(选择).我想限制选择器的使用,并想通过在所有SELECT
上使用单个类选择器来实现这一点;通过找出由其索引更改的SELECT
.因此,更改的SELECT[i]
仅会更改SELECT[i+1]
(而不是以前的SELECT[i-1]
).
I am trying to create multiple dependent dropdowns (selects) with a unique way. I want to restrict the use of selectors and want to achieve this by using a single class selectors on all SELECT
s; by figuring out the SELECT
that was changed by its index. Hence, the SELECT[i]
that changed will change the SELECT[i+1]
only (and not the previous ones like SELECT[i-1]
).
对于这样的html:
<select class="someclass">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class="someclass">
</select>
<select class="someclass">
</select>
第一个cc以外的SELECT
会通过AJAX获得某些信息.
where the SELECT
s other than the first one will get something via AJAX.
我看到以下Javascript为我提供了正确的SELECT
的正确值,并且i
的值也对应于正确的SELECT
.
I see that the following Javascript gives me correct value of the correct SELECT
and the value of i
also corresponds to the correct SELECT
.
$(function() {
$(".someclass").each(function(i) {
$(this).change(function(x) {
alert($(this).val() + i);
});
});
});
请注意,我确实想要最小选择器方法.我只是无法确定如何解决这个问题.我应该使用数组吗?像先将所有SELECTS
存储在数组中,然后选择那些SELECTS
吗?
Please note that I really want the minimum selector approach. I just cannot wrap my head around on how to approach this. Should I use Arrays? Like store all the SELECTS
in an Array first and then select those?
我相信,由于上述代码已经通过了索引i
,因此也应该有一种不使用数组的方法.
I believe that since the above code already passes the index i
, there should be a way without Arrays also.
谢谢. AJ
更新:
以下是更好的描述:
- 页面上有超过2个带有"someclass"类的"SELECT". SELECT [0]最初具有一些值,并且其后继项为空,因为它们将根据各自直系祖先的值进行更改.
- 如果SELECT [i]中发生更改,则会触发一个事件,并向SELECT [i + 1]中填充相应的OPTION. 如果
- SELECT [i + 2]和后续的继承者之前有任何数据,则会被重置.因此,仅填充直子,但将重置后续子.
我希望我能说清楚.如果您需要进一步说明我想要的内容,请告诉我.
I hope I articulated well. Please let me know if you need more clarification on what I want.
推荐答案
编辑:更正的版本.
$(function() {
var $all = $('.someclass'); // Reference all the selects
var last = $('.someClass').length - 1; // Store index of last select
$(".someclass").change(function() {
var $th = $(this); // Reference the changed select
var index = $all.index($th); // Grab the index of the changed select
if(index != last) { // If the selected wasn't the last,
var $next = $all.eq(index + 1) // reference the next select
$all.filter(':gt(' + index + ')').empty(); // and empty all selects greater than the
// index of the changed one.
// This will include the one that is about
// to be populated.
// Then presumably perform some AJAX
// based on $th.val(); to populate
// $next with options.
}
});
});
这篇关于具有单个类(没有其他选择器)的从属下拉列表(链接的选择)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!