2011-08-09 129 views
3

是否可以通过按下按钮来选择特殊的<option>项目?带按钮的jQuery选择选项

例如:

<a id="item1" href="#">Item 1</a> 
<a id="item2" href="#">Item 2</a> 
<a id="item3" href="#">Item 3</a> 

<form> 
....... 
<select id="items" name="items"> 
<option value="1">I dont know</option> 
<option value="2">Item 1</option> 
<option value="3">Item 2</option> 
<option value="4">Item 3</option> 
</select> 
......... 

</form> 

如果按下第二按钮比形式自动地选择第二个选项。可能吗?

回答

3

这是做一个简单的jQuery的方式。

$('a').click(function() { 
    var select_num = $(this).index() + 1; 
    $('#items option').eq(select_num).attr('selected', 'selected'); 
}); 

下面是示例fiddle.

0

尝试此(第2项联系在列表中选择项目2):为每个按钮/链路

$('#item2').click(function(){ 
    $('#items option:nth-child(3)').attr('selected', 'selected'); 
}); 

和类似的功能。

+0

等等是这样的。关于如何使它们动态工作的任何想法? – Phil

+0

看看我的帖子,了解如何动态地做到这一点。 – Kyle

0

试试这个:

$('#item1').click(function() { 
    $('#items option[value="2"]').attr('selected', true); 
}); 

在这里看到:http://jsfiddle.net/RVUDa/

+0

这是静态的... – Phil

0

一个id包裹你的标签块元素。当你需要点击很多项目时,这将有助于提高它的效率,因为对于列表中的每个项目,它只有一个监听器,而不是一个监听器。

<div id="buttons"> 
    <a id="item1" href="#">Item 1</a> 
    <a id="item2" href="#">Item 2</a> 
    <a id="item3" href="#">Item 3</a> 
</div> 

然后为你的jQuery代码,你可以这样做:

$('#buttons').click(function(e) 
{ 
    var num = $(e.target).index() + 1; 
    $('option:nth-child(' + num + ')', '#items').attr('selected', 'selected'); 
});