2013-02-06 54 views
0

比方说,我有以下链接和下拉菜单:更改下拉选项单击

<a href="#contact">Send a mail to mother!</a> 
<a href="#contact">Send a mail to father!</a> 
<a href="#contact">Send a mail to sister!</a> 
<a href="#contact">Send a mail to brother!</a> 

<form id="contact"> 
    <select id="recipient"> 
     <option value="[email protected]">Mother</option> 
     <option value="[email protected]">Father</option> 
     <option value="[email protected]">Sister</option> 
     <option value="[email protected]">Brother</option> 
    </select> 
</form> 

基本上,我想每一个环节更改为相应的选择选项。

为了给你一个上下文,现在我在页面的末尾有一个表单,并且在开始时我有几个电子邮件链接。当有人点击一个链接时,它会滚动(锚点)到表单。该表单具有此下拉菜单以选择收件人。我希望它不仅滚动到表单(已完成),而且还可以根据单击的链接自动更改选项。

我该如何做到这一点?

+0

[你有什么尝试](http://whathaveyoutried.com/)? –

回答

4

一个data-select属性添加到这些链接:

<a href="#contact" data-select="[email protected]">Send a mail to mother!</a> 
<a href="#contact" data-select="[email protected]">Send a mail to father!</a> 
<a href="#contact" data-select="[email protected]">Send a mail to sister!</a> 
<a href="#contact" data-select="[email protected]">Send a mail to brother!</a> 

然后使用点击链接的值来设置的值元素:

var $select = $('#recipient'); 
$('a[href="#contact"]').click(function() { 
    $select.val($(this).data('select')); 
}); 

这里的小提琴:http://jsfiddle.net/Dw6Yv/


如果您不想添加这些data-select属性您的标记,你可以使用这个:

var $select = $('#recipient'), 
    $links = $('a[href="#contact"]'); 

$links.click(function() { 
    $select.prop('selectedIndex', $links.index(this)); 
}); 

这里的小提琴:http://jsfiddle.net/Bxz24/

请记住这将要求您的链接与select选项的顺序完全相同。

+0

正是我想要的,再次感谢你:) – coldpumpkin

+0

@Joseph如果下拉是在另一个页面,它会工作与否? –

3

如果订单是百达一样,你可以做到这一点

$("a").click(function(){ 
    $("#recipient").prop("selectedIndex", $(this).index()); 
}); 

由链路上定义的索引,否则这样做:

<a href="#contact" data-index="0">Send a mail to mother!</a> 
<a href="#contact" data-index="1">Send a mail to father!</a> 
<a href="#contact" data-index="2">Send a mail to sister!</a> 
<a href="#contact" data-index="3">Send a mail to brother!</a> 

<form id="contact"> 
    <select id="recipient"> 
     <option value="[email protected]">Mother</option> 
     <option value="[email protected]">Father</option> 
     <option value="[email protected]">Sister</option> 
     <option value="[email protected]">Brother</option> 
    </select> 
</form> 

$("a").click(function(){ 
    $("#recipient").prop("selectedIndex", $(this).data("index")); 
}); 
+0

谢谢,这个作品:) – coldpumpkin