在jQuery / Rails中第一个选择菜单上的更改事件后选择下一个选择菜单

时间:2011-04-19 01:09:41

标签: jquery jquery-selectors

我正在尝试在具有多个动态基于ajax的选择的页面上干掉一些jQuery(就像在动态选择make,model等的自动网站上一样)。就目前而言,我的页面看起来大致如下:

<p>
  <label>...</label>
  <select id="selectA">...</select>
</p>
<p>
  <label>...</label>
  <select id="selectB">...</select>
</p>

我的jQuery看起来像:


$("select#selectA").change(function(){
  // If this works, selectB should turn red.
  $(this).next().css('background-color', 'red');
});

但是selectB永远不会变红。我已经为选择器尝试了各种组合,例如初始和 "select", "p select", "p select#id",选择器字段中的"select#id"next()。我错过了一些明显的东西吗谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

$(this).parent().next().children('select').css('background-color', 'red');

此外,如果您要动态添加元素,则可能需要切换到live

$("select").live('change',function(){
  // if this works...
  $(this).parent().next().children('select').css('background-color', 'red');
});

编辑:如果可以,请使用css类作为您应该选择的选择。它更容易(在某些情况下也很有用)。假设您将添加css类ajaxselect。您可以将此功能更改为:

$('.ajaxselect').live('change',function(){
  // if this works...
  $(this).parent().next().children('.ajaxselect').css('background-color', 'red');
});

Edit2:您可以看到working example here