繁体   English   中英

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

[英]Change dropdown option with jQuery/Javascript on link click

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

<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>

基本上,我希望每个链接都更改为各自的选择选项。

为了给您一个背景,现在页面末尾有一个表格,开始时有几个电子邮件链接。 当某人单击链接时,它将滚动(锚定)到表单。 表单具有此下拉列表以选择收件人。 我希望它不仅滚动到表单(已完成),还希望基于单击的链接自动更改选项。

我该如何实现?

向这些链接添加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>

然后使用单击链接的值来设置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());
});

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

<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="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>

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

另外还有一种使用label选项的方法,这种方法可以确保即使没有html5 data也可以使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM