我有一个下拉框,根据选择,我应该填充特定于那一年的内容。在任何时候我都只能填充一年的内容,我需要根据选择隐藏其余内容。我应该如何使用 Jquery 对此进行编码
<div style="margin:4px 0 0 0;">
<label> Select Year </label>
<select name="select_Release">
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
</select>
</div>
<div>Some 2011 content to display</div>
<div>Some 2010 content to display</div>
<div>Some 2009 content to display</div>
<div>Some 2008 content to display</div>
<div>Some 2007 content to display</div>
<div>Some 2006 content to display</div>
<div>Some 2005 content to display</div>
最佳答案
这里的工作示例:http://jsfiddle.net/FDpmb/1/
jQuery:
//traverse the DOM once to get all of your div tags per year
var years = $('.options > div')
//define a function that will show/hide the year content
var check = function($select)
{
var year = $select.val();
years.hide();
$('div[data-year="' + year + '"]').show();
}
//get the instance of your select box
var element = $('#select_Release');
//bind an event handler
element.change(function () { check($(this)); });
//and we want to show the correct content initially, so call our change function
check(element);
稍微修改了标记(注意选择框上的 id
,以及额外的 div
标签和 data-year
属性):
<div style="margin:4px 0 0 0;">
<label> Select Year </label>
<select id="select_Release" name="select_Release">
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
</select>
</div>
<div class="options">
<div data-year="2011">Some 2011 content to display</div>
<div data-year="2010">Some 2010 content to display</div>
<div data-year="2009">Some 2009 content to display</div>
<div data-year="2008">Some 2008 content to display</div>
<div data-year="2007">Some 2007 content to display</div>
<div data-year="2006">Some 2006 content to display</div>
<div data-year="2005">Some 2005 content to display</div>
</div>
关于javascript - Jquery中如何编写下拉菜单逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876299/