【问题标题】:Change dropdown option with jQuery/Javascript on link click单击链接时使用 jQuery/Javascript 更改下拉选项
【发布时间】:2013-01-22 03:32:31
【问题描述】:

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

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

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

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

我怎样才能做到这一点?

【问题讨论】:

标签: javascript jquery select drop-down-menu


【解决方案1】:

为这些链接添加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 选项的顺序完全相同。

【讨论】:

  • @Joseph 如果下拉菜单在另一个页面中,它会起作用吗?
【解决方案2】:

如果顺序始终相同,您可以这样做

$("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"));
});

【讨论】:

    【解决方案3】:

    还有there is another way 使用label 选项,这确保在没有html5 data 的情况下也可以工作。

    【讨论】:

    • 谢谢,这也很好:)
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2010-11-28
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    相关资源
    最近更新 更多