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

时间:2010-07-05 01:23:39

标签: 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(我将在以后),它将无效。

我理想的行为是单击select并让它显示但没有跳转可用选项。我想也许我的show()是罪魁祸首,但它使代码变得简单。

1 个答案:

答案 0 :(得分:0)

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

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