jquery ajax gets fired on load instead of on blur

2019-08-28 04:07发布

I have a function called applyToDetailRows, which I call on load, as well as when the input section of my page gets re-drawn via ajax. this function, attaches a bunch of events to the input fields that get drawn. One of the events on a field is blur, which triggers an ajax call to fetch student info. The problem is that the blur ajax trigger fires every time the page loads for each field, rather than firing on blur. And this only happens if the function is defined inside of applyToDetailRows. If I pull it out of applyToDetailRows, it works fine.

one thing to note is that I also have auto-complete defined in applyToDetailRows in the similar manner, and it works fine. But not this.

    function applyToDetailRows() {
        $(":input[data-getstudent]").each(function() {
            $(this).on('blur', function () {
                var elem = this;
                $.ajax({
                    url: $(elem).attr('data-getstudent'),
                    dataType: "json",
                    data: {
                        studentNumber: $(elem).val()
                    },
                    success: function (result) {
                    }
                });
            });
        });
    }

/* some other definitions */

//applyToDetailRows called

applyToDetailRows();

1条回答
甜甜的少女心
2楼-- · 2019-08-28 04:50

You would prefer to use event delegation instead of re-applying the function after each request since it is possible you may be binding it wrong or more than once.

$(document).on("blur", ":input[data-getstudent]", function(){
  /* AJAX */
});

You can replace document with a common parent of all the input elements that is closer in the DOM tree to them than it.

查看更多
登录 后发表回答