javascript - 是否可以将 `event.preventDefault()` 与 jQuery 的 `select` 元素一起使用?

标签 javascript jquery

我的下拉菜单依赖于其他下拉菜单。

我决定计算点击的依赖关系,除了它有一个令人讨厌的副作用,即显示选项元素,然后它们很快消失并且下拉列表调整大小。

我想知道是否可以在点击时使用 event.preventDefault() ,然后在计算出可能的选项后手动调用 click() 事件。

好像没用。

解决这个问题的最佳方法是什么?

这是我的 jQuery

var $selects = $('form#main select');


$selects.click(function(event) {
    var $thisSelect = $(this);
    event.preventDefault(); // Doesn't cancel anything

    // Get the other selected values
    var selectedIndexes = [];
    $selects.not($thisSelect).each(function() {
        var index = $(this)[0].selectedIndex;
        selectedIndexes.push(index);
    });

    // I think this is where the problem lies -
    // it is my lazy way of showing them all again before I hide
    // what needs to be hidden
    $selects.find('option').show();

    // Remove them from this dropdown
    $.each(selectedIndexes, function(i, index) {

        $thisSelect.find('option').eq(index).hide();

    });

}).click();

谢谢!

更新

很抱歉造成任何困惑,您可以在 JSBin 上看到此行为.

您无法从另一个中选择一个 - 即它们永远不会具有相同的值。

在我的 Firefox 3.6.6 中,您会看到它在计算它可能显示的内容时出现丑陋的跳跃。

我意识到只有 2 个 select 才能使用 .siblings().hide(),但如果我需要超过 2 个(其中我稍后会讲)。

我的理想行为是单击选择并让它显示而不跳转可用选项。我认为也许我的 show() 是罪魁祸首,但它使代码保持简单。

最佳答案

我仍然不确定我是否完全理解你的问题。但这可能对你有用。 如果您有问题,我很乐意帮助您,但我需要更好的解释。

HTML

<select id="left">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<select id="right">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>​

JavaScript

$(document).ready(function() {

    var left = $("#left");
    var right = $("#right");

    left.change(function(){
        if (right.val() == $(this).val()) {
            alert("error");
            $(this).attr("selectedIndex", "0");
        }
    });

    right.change(function() {
        if (left.val() == $(this).val()) {
            alert("error");
            $(this).attr("selectedIndex", "0");
        }
    });
});

关于javascript - 是否可以将 `event.preventDefault()` 与 jQuery 的 `select` 元素一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3176812/

相关文章:

javascript - 如何在firebase中的数组中仅设置一个元素

javascript - 禁用 JS 时 Bootstrap 折叠行为的回退

javascript - 行列式函数中的 NaN?

c# - 使用 Script# 编译代码(独立)

javascript - JavaScript 中的 array.contains(array)

javascript - jquery中如何调用$(function)

javascript - 使用 jQuery 读取下拉选择字段中的选定值

javascript - 为什么 <div> 不移动?

javascript - Grails 渲染内容动态访问 id 元素

javascript - Jquery 选择器,其中属性 ID 不在