更改下拉式选项与jQuery / Javascript在链接点击 [英] Change dropdown option with jQuery/Javascript on link click
问题描述
假设我有以下链接和下拉列表:
Let's say I have the following links and dropdown:
<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="mother@mail.com">Mother</option>
<option value="father@mail.com">Father</option>
<option value="sister@mail.com">Sister</option>
<option value="brother@mail.com">Brother</option>
</select>
</form>
基本上我希望每个链接都更改为相应的选择选项。
Basically I want each link to change to the respective selection option.
为了给你一个上下文,现在我在一个页面的末尾有一个表单,一开始我有几个电子邮件链接。当有人点击链接时,它将滚动(锚定)到表单。该表单有此下拉列表来选择收件人。我希望它不仅滚动到表单(已经完成),还可以根据点击的链接自动更改选项。
To give you a context, right now I have a form in the end of a page, and in the beginning I have a couple of e-mail links. When someone clicks a link, it'll scroll (anchor) to the form. The form has this dropdown to select the recipient. I want it to not only scroll to the form (which is already done) but also to automatically change the option based on the link clicked.
我该如何实现?
推荐答案
将 data-select
属性添加到这些链接: p>
Add a data-select
attribute to those links:
<a href="#contact" data-select="mother@mail.com">Send a mail to mother!</a>
<a href="#contact" data-select="father@mail.com">Send a mail to father!</a>
<a href="#contact" data-select="sister@mail.com">Send a mail to sister!</a>
<a href="#contact" data-select="brother@mail.com">Send a mail to brother!</a>
然后使用点击链接的值设置 select的值
元素:
Then use the value of the clicked link to set the value of the select
element:
var $select = $('#recipient');
$('a[href="#contact"]').click(function () {
$select.val( $(this).data('select') );
});
这是小提琴: http://jsfiddle.net/Dw6Yv/
如果你不要将这些 data-select
属性添加到您的标记中,可以使用以下内容:
If you don't want to add those data-select
attributes to your markup, you can use this:
var $select = $('#recipient'),
$links = $('a[href="#contact"]');
$links.click(function () {
$select.prop('selectedIndex', $links.index(this) );
});
这是小提琴: http://jsfiddle.net/Bxz24/
请记住,这将需要您的链接完全相同订单为选择
选项。
Just keep in mind that this will require your links to be in the exact same order as the select
options.
这篇关于更改下拉式选项与jQuery / Javascript在链接点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!