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

col*_*kin 0 javascript jquery select drop-down-menu

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

我怎样才能做到这一点?

Jos*_*ber 5

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http : //jsfiddle.net/Dw6Yv/


如果您不想将这些data-select属性添加到标记中,可以使用以下命令:

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

这是小提琴:http : //jsfiddle.net/Bxz24/

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