jQuery .change()事件只被触发一次 [英] jQuery .change() event is only fired once

查看:137
本文介绍了jQuery .change()事件只被触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,在DOM准备好时从数据库中检索项目名称。每个项目都会添加到html < form> 中的< select>< option> 中。填充列表后,用户可以选择项目标题,该项目标题将从特定于该项目的数据库中请求剩余信息。

I have an application that retrieves Project names from a database when the DOM is ready. Each Project is added to a <select><option> in an html <form>. Once the list is populated the user can select a project title, which will request the remaining information from the database specific to that project.

为实现此目的,我正在使用 $ .change() jQuery方法。不幸的是,只有在创建< select> 元素并将其添加到DOM时才会触发该事件。从列表中选择另一个项目不会触发事件,因此不会触发 $。post()调用。

To achieve this I'm using the $.change() jQuery method. Unfortunately, the event is only fired once when the <select> element is created and added to the DOM. Selecting another project from the list does not fire the event, and therefore does not trigger a $.post() call.

$(function(){
    getProjects();
    var firstLoad = true;

    $("select").change(retrieveProject); // Removed parenthesis based on answers

    // On page load, get project names from the database and add them to a Select form element
    function getProjects() {
        var selectionList;
        $.getJSON("php/getProjects.php", function (data) {
            selectionList = "<form><select>";
            for (var i = 0; i < data.length; i++) {
                selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
            }
            selectionList += "</select></form>";
        }).complete(function() {
           $('#project-selection-menu').append(selectionList).removeClass('hidden');
           firstLoad = false;
        });
    }

    function retrieveProject() {
        if ( firstLoad == true ){
            alert(firstLoad); // This alert fires
            return false;
        } else {
            alert(firstLoad); // This alert doesn't fire
            $.post("php/getProjects.php", function (data) { // This should have been "php/retrieveProject.php"!
                // Do stuff with the returned data
            }).complete(function() {
               console.log("Success.");
            });
        }
    }
)};


推荐答案

您没有正确设置事件处理程序:

You're not setting up the event handler properly:

$("select").change(retrieveProject);

在您的代码中,您调用retrieveProject函数,并且该函数调用的返回值作为更改处理程序传递(当然没有效果)。这就是为什么事件是在页面加载时生成的原因。

In your code, you were calling the "retrieveProject" function, and the return value from that function call was being passed as the "change" handler (and of course having no effect). That's why it appeared that the event was being generated upon page load.

当你使用函数作为时,你不要在函数引用后使用()—它是您想要的引用本身(在本例中为函数名称)。这就是需要传递给jQuery的东西。

When you're working with a function as a value, you don't use () after the function reference — it's the reference itself (the function name, in this case) that you want. That's what needs to be passed to jQuery.

还—这很重要—确保您的代码在就绪或加载处理程序中运行,或者您的< script> 在之后页面上的< select> 元素。如果脚本在文档头中,那么它将在解析DOM之前运行,并且它将无效。 (处理这种情况的另一种方法是使用另一个答案中建议的 .on()委托表格。)

Also — and this is important — make sure that your code is run either in a "ready" or "load" handler, or else that your <script> comes after the <select> element on the page. If the script is in the document head, then it'll run before the DOM is parsed, and it'll have no effect. (Another way to deal with that would be to use an .on() delegated form as suggested in another answer.)

更多:当您在getProjects中获取内容时,看起来您正在覆盖< select> 元素。因此,您一定要使用委托表格:

More: it looks like you're overwriting your <select> element when you fetch the content in "getProjects". Thus, you should definitely use the delegated form:

$(document).on("change", "select", retrieveProject);

此外,您应该在getProjects中使用局部变量:

Also, you should be using local variables in "getProjects":

function getProjects() {
    var selectionList; // keep this local to the function - implicit globals are risky

    $.getJSON("php/getProjects.php", function (data) {
        selectionList = "<form><select>";
        for (var i = 0; i < data.length; i++) {
            selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
        }
        selectionList += "</select></form>";
    }).complete(function() {
       $('#project-selection-menu').append(selectionList).removeClass('hidden');
       firstLoad = false;
    });
}

这篇关于jQuery .change()事件只被触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆