0

请问有人能在下面的代码中发现我做错了什么吗?我知道这不是最优雅的代码,但我目前正在做五件事,我想我可以快速敲掉这个简单的代码,让它从我的盘子里消失。

我要做的就是>>如果选择的项目类型等于特定值,则显示一个字段集,如果它不等于该值,则隐藏该字段集。很简单吧?如果选择的值不匹配,我无法隐藏字段集。

请注意,我是 jquery 的新手,但这是一个基本的 if/else - 我在这里做错了什么?先感谢您。

$('fieldset#section-841', 'fieldset#section-837' ).hide();
var DM_projtype = new Array(
        {value : 'Direct Mail', sect_id : 'fieldset#section-841'},
        {value : 'Multiple items', sect_id : 'fieldset#section-837'}
    );
$('select#3596').change(function() {
    var getDM_projType = $(this).val();
    var sect_id = '';
     for (var i = 0; i < DM_projtype.length; ++i) 
        {
            if (DM_projtype[i].value == "Direct Mail" )
                {
                    sect_id = DM_projtype[i].sect_id;
                   $(sect_id).show();
                }
            else
                {
                   $('fieldset#section-841').hide(); 
                }
            if (DM_projtype[i].value == "Multiple items" )
                {
                    sect_id = DM_projtype[i].sect_id;
                   $(sect_id).show();
                }
            else
                {
                   $('fieldset#section-837').hide(); 
                }
       }
  });
4

1 回答 1

2

You have structured your code against logic it seems - each element of your array is going to be processed through the loop, so you execute both an if and else of each block set you contain. You should instead do this:

$('select#3596').on('change', function() // do .change() if using a lower jQuery version
{
    var thisVal = $(this).val(); // Assuming this returns 'Direct Mail' or 'Multiple Items'

    $(DM_projtype).each(function()
    {
         $(this.sect_id).hide();

         if(this.value == thisVal)
            $(this.sect_id).show();
    });
});
于 2012-04-24T15:08:58.640 回答