如果您不知道ID,请启用顺序选择菜单

我有一组Select Menus,它们是根据产品数据库(WooCommerce)中的变体构建的。 可以有任意数量,通常从3到8.简单如:

 Choose an option... Test Test 2   Choose an option... Test Test 2   Choose an option... Test Test 2  

我想根据在上一个菜单中进行的选择顺序启用它们。 我不需要在新菜单中更改任何选项 – 我只需要启用它。

因此, 如果Select1≠“选择一个选项…”,则启用Select2,如果Select2≠“选择一个选项…”,则启用Select3。

问题是我无法预测ID会是什么,所以我不能使用以下变体:

 $(function() { $("#theID").change(function() { if ($(this).val() == "Choose an option…") { $("#theID_2").prop("disabled", true); } else $("#theID_2").prop("disabled", false); }); }); 

那么我的问题是:有没有办法在不事先知道ID的情况下使用jQuery单独启用/禁用Select菜单?

这只是一个疯狂的想法吗? 我是否会更好地尝试在运行中构建javascript,读取ID是否已写入Selects服务器端?

如果选择按顺序排列,则可以使用JQuery.next():

http://api.jquery.com/next/

 $("select").on('change', function(){ $(this).next("select").prop("disabled", false); }); 

例:

http://jsfiddle.net/Zv72Y/

如果所有这些选择在一个容器中,那么您可以为每个容器附加一个事件监听器,这将解锁下一个选择元素:

HTML:

 

javascipt的:

 $('.container').on('change','select', function(){ $(this).nextAll('select').first().removeAttr('disabled'); }); 

$().nextAll() – 获取匹配元素集中每个元素的所有后续兄弟,可选择由选择器过滤。

.first()将选择当前的第一个选择并从他的attritbute中删除disabled

示例:jsFiddle