在链接点击时使用jQuery / Javascript更改下拉选项

假设我有以下链接和下拉列表:

Send a mail to mother! Send a mail to father! Send a mail to sister! Send a mail to brother! 
Mother Father Sister Brother

基本上我希望每个链接都更改为相应的选择选项。

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

我怎样才能做到这一点?

向这些链接添加data-select属性:

 Send a mail to mother! Send a mail to father! Send a mail to sister! Send a mail to brother! 

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

 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选项的顺序完全相同。

如果订单总是相同,你可以这样做

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

否则,通过在链接上定义索引来执行此操作:

 Send a mail to mother! Send a mail to father! Send a mail to sister! Send a mail to brother! 
$("a").click(function(){ $("#recipient").prop("selectedIndex", $(this).data("index")); });

还有另一种使用label选项的方法,这肯定也可以没有html5 data