0

我有一个使用haml的表单中的下拉菜单代码

= f.select :contact_type, options_for_select(['String','Email','Phone','Textarea','Boolean', 'Multi Select'],
 selected: @contact_object.contact_type), onchange: "showDiv(this, @i)"
- if @contact_object.contact_type == 'Boolean'
  %div{:id=>"options_for_boolean_#{@i}"}
    %li
      =f.label :first_boolean_option do
        Field
        %span{:class => "item-number"}
          =@i
        First opt.
      =f.text_field :first_boolean_option, :placeholder => "Enter First option:"
    %li
      =f.label :second_boolean_option do
        Field
        %span{:class => "item-number"}
          =@i
        First opt.
      =f.text_field :second_boolean_option, :placeholder => "Enter Second option:"
- if @contact_object.contact_type == 'Multi Select'    
  %div{:id=>"options_for_multiselect_#{@i}"}
    %li
      =f.label :multiselect_options do
        Field
        %span{:class => "item-number"}
          =@i
        Multiselect opt.
      =f.text_area :multiselect_options, :placeholder => "Enter all options separated with comma:"

这里@i 是迭代器值。我在这里要做的是,上面的代码在循环中。每个循环都有一个带有选定值的下拉菜单。当用户选择布尔或多选选项时,它将向他显示相应的 div 以获取更多详细信息。因此,如果用户选择第二个下拉框的布尔选项,它应该在第二个迭代层中显示布尔值的 div。使困惑?这是更简单的解释

drop-down-box1
  div1 for boolean
  div1 for multi select

drop-down-box2
  div2 for boolean
  div2 for multi select

drop-down-box3
  div3 for boolean
  div3 for multi select

*默认隐藏所有 div。如果用户选择“drop-down-box2”的“boolean”,它应该显示“div2 for boolean”怎么做?

到目前为止,我的 jQuery 代码是

:javascript
$(document).ready(function() {
  function showDiv(changing,numb) {
    var sel_val = changing.options[changing.selectedIndex].val();
    if (sel_val == 'Boolean') {
      $('#options_for_boolean_' + numb).show();
    } else if (sel_val == 'Multi Select') {
        $('#options_for_multiselect_' + numb).show();
    } else {
        $('#options_for_boolean_' + numb ).hide();
        $('#options_for_multiselect_'+ numb).hide();
    } 
  }
});
4

1 回答 1

0

实际上问题出在 select 标签的 haml 代码中,onchange 事件未正确触发。我们可以将此问题称为“ onchange html 选项未出现在浏览器中”。

下面这个概念对我帮助很大。

:onchange 是一个 html_option。这是选择的语法:

**

选择(对象,方法,选择,选项={},html_options={})

**

所以在我的情况下:

= f.select :contact_type, options_for_select(['String','Email','Phone','Textarea','Boolean', 'Multi Select'], selected: @contact_object.contact_type),{},
  :onchange => "showDiv(#{@i});"

注意那里的空哈希代表选项。此外,我将我的 javascript 代码更改为下面的

:javascript
$(document).ready(function() {
  function showDiv(numb) {
    var sel_val = $('#userservicepage_contactsettings_attributes_' + numb + '_contact_type').val();
    if (sel_val == "Boolean") {
      $('#options_for_boolean_' + numb).show();
    } else if (sel_val == "Multi Select") {
      $('#options_for_multiselect_' + numb).show();
    } else {
      $('#options_for_boolean_' + numb ).hide();
      $('#options_for_multiselect_'+ numb).hide();
    }
  }
});

结果,整个事情变得充满活力。

于 2012-08-06T21:25:54.180 回答