2011-09-01 66 views
1

我希望根据下拉列表显示内容。因此,2005选择只显示与2005年的最新内容等jQuery根据下拉列表显示内容

HTML:

<select id="year" name="Year"> 
     <option value="#" selected="selected">Year...</option> 
     <option value="#">2007</option> 
     <option value="#">2006</option> 
     <option value="#">2005</option> 
    </select> 

-

<li class="pr"> 
    <a class="image" href="image.jpg" width="50" height="50" /></a> 
    <span class="date">2006</span> 
</li> 

<li class="pr"> 
    <a class="image" href="image.jpg" width="50" height="50" /></a> 
    <span class="date">2007</span> 
</li> 

看了一下这个: jQuery dropdown hide show div based on value

,但似乎矫枉过正?

+0

我不认为你链接的一个是矫枉过正,这是相当简单的。您可以简化hideAllDivs()方法,因为您正在使用类,并且不需要列出要隐藏的每个单独的ID。 – CashIsClay

+0

虽然日期列表是可变的,并且可能是20个左右,但链接的方法将意味着写入一个巨大的列表。 – BobFlemming

+0

根本不是。隐藏ALL $(“。pr”),然后显示$(“span.date”)的父项,其中值与选定的选项相匹配(下面的答案之一已经说明了如何执行此操作)。虽然这个概念与你所关联的问题相同。 – CashIsClay

回答

3
$('select#year').change(function(){ 

    theVal = $(this).children(':selected').text(); 
    $('span.date').each(function(){ 

     if($(this).text()==theVal){ 
      $('li.pr').hide(); 
      $(this).parent().show(); 
     } 
    }); 
}); 

对不起,这一个应该与你有的HTML,旧的基于价值的工作。

0

很多方法可以做到这一点,其中之一是

<select id="year" name="Year"> 
      <option value="#" selected="selected">Year...</option> 
      <option value="2007">2007</option> 
      <option value="2006">2006</option> 
      <option value="2005">2005</option> 
</select> 

戴上ID在贵丽的

<li class="pr" id="2006"> 
    <a class="image" href="image.jpg" width="50" height="50" /></a> 
    <span class="date">2006</span> 
</li> 

<li class="pr" id="2007"> 
    <a class="image" href="image.jpg" width="50" height="50" /></a> 
    <span class="date">2007</span> 
</li> 

了jQuery的

$(function() { 
    $('ul li').hide(); 
    $('#year').change(function() { 
     var year = $(this).val(); 
     $('#'+ year).show(); 
    }); 
}); 
0

下面是一些快速的JS,在jsbin测试,source

$('#year').live('change', function(){ 
    var Year = $(this).val(); 
    $('li.pr').hide(); 
    $('span.date').each(function(){ 
    if ($(this).text() == Year){ 
     $(this).parent().show(); 
     return false; 
    } 
    }); 
}); 

但你需要改变你的HTML有点为这个工作:

<option value="#" selected="selected">Year...</option> 
<option>2007</option> 
<option>2006</option> 
<option>2005</option> 
相关问题