jQuery事件触发一次,然后再也不会触发

jQuery event fires once, then never again

本文关键字:然后 再也不 一次 事件 jQuery      更新时间:2023-09-26

我已经在一个简单的JQuery事件处理程序上挣扎了几个小时。我的事件处理程序只在页面加载时触发一次,无论事件或与选择框的交互如何,都不会再次触发。延迟时,警报(当我有一个时(显示第一个选择选项。否则,警报为空。

我想要的只是从 AJAX 加载选择框,以及用户选择触发另一个 AJAX 调用。

.HTML:

<select id="connection" name="Connection"></select>
<div id="testme" style="background: #CCC; width:100%; height:50px;position:relative;color:red">testing</div>

Javascript:

$(document).ready(function () {
    // Event handler. Tried as a separate function and as a parameter to $.on(...)
    function connectionSelected() {
        var str = $('#connection option:selected').text();
        alert(str);
        $("#testme").text(str);
    }
    var $connectionSelect = $('#connection');
    //$connectionSelect.selectmenu(); // Tried enabling/disabling
    // Tried this and all JS code inside and outside of $(document).ready(...)
    $.when(
    $.ajax({
        dataType: "JSON",
        url: '@Url.Content("~/API/ConnectionHint")', // The AJAX call (using ASP Razor) works fine
        success: function(data) {
            // This function is always called and works
            var items = [];
            $.each(data, function(key, val) {
                items.push("<option value='" + key + "'>" + val + "</option>");
            });
            $connectionSelect.append(items.join(""));
            // Tried setting up the event handler here
        },
        error: function() {
            $connectionSelect.html('<option id="-1">none available</option>');
        }
    })
    ).then(function() {
        //$("#connection option").blur(connectionSelected()).change();
        $("#connection").on("change", connectionSelected());
    });
});

尝试了事件处理程序的数十种变体,几个事件,在 deferred.done 和 deferred.then 的内部和外部,例如:

$connectionSelect.selectmenu({
    change: function (event, data) {
        $('#connection').change(function () {
            var str = "";
            $('#connection').each(function () {
                str += $(this).text() + "<br>";
            });
            $("#testme").text(str);
        });
    }
});

我通常编写后端代码,只熟悉 JQuery 的部分内容,这让我发疯。我已经在SO和其他地方查看了30多个相关问题,例如

  • Jquery 事件触发一次
  • Jquery .change(( 函数不适用于动态填充的 SELECT 列表
  • http://jqueryui.com/selectmenu/#product-selection

任何想法都值得赞赏。

而不是

$("#connection").on("change", connectionSelected());

尝试

$("#connection").on("change", connectionSelected);

请注意,在第二个中,我通过引用传递函数处理程序,而不是调用它。

相关文章: