简体   繁体   English

Javascript中的ajax响应后未调用下拉事件

[英]Dropdown event not called after ajax Response in Javascript

Here is my code: 这是我的代码:

 $.ajax({ url: "server.do?button=go&flag=false", type: "GET", success: function(data) { var respContent = ""; respContent += data; $("#ajaxResponse").show(); $("#ajaxResponse").html(data); } }); 
 <span id="ajaxResponse" style="display:none"></span> 

This is then the HTML I have which is binded to ajaxResponse span: 这是我绑定到ajaxResponse span的HTML:

 <span style="" id="ajaxResponse"><select tabindex="12" id="aId" name="aId"><option value="ANY">ANY</option><option value="1">ABC</option><option value="2">XYZ</option></select></span> 

As you can see above, from the server I am sending back the HTML response for a dropdown. 如上所示,我正在从服务器发回HTML响应以进行下拉。 The dropdown is well formed and is appended to the ajaxResponse div. 下拉列表格式正确,并附加到了ajaxResponse div中。 The dropdown appears and is well formed in the developer tools browser control. 出现下拉列表,该下拉列表在开发人员工具浏览器控件中的格式正确。 However the dropdown does not fire the jQuery on change event. 但是,下拉列表并不会在发生更改事件时触发jQuery。 I think the DOM has already loaded and jQuery is unable to find the ID for the On change event to fire.Which means: 我认为DOM已经加载并且jQuery无法找到触发on change事件的ID,这意味着:

  $("#aId").change(function(e) { //How do i fire this event ?? alert('I am never called'); }); 

My question is how to call the above function for the dropdown sent from server side ? 我的问题是如何为服务器端发送的下拉列表调用上述函数?

Try this : 尝试这个 :

$.ajax({
    url: "server.do?button=go&flag=false",
    type: "GET",
}).done(function (data) {
    var respContent = "";
    respContent += data;
    $("#ajaxResponse").show();
    $("#ajaxResponse").html(data);
})
.fail(function () {
    console.log("error");
});

Try this: 尝试这个:

jQuery 1.7 onwards use "on", for prior version you can use "live" jQuery 1.7及更高版本使用“ on”,对于以前的版本,您可以使用“ live”

$(document).on('change','#aId', function(e) { //How do i fire this event ?? alert('I am never called'); });

The element (#aId) does not available when the document ready.So the change event will not assigned, for that we need to bind the change event dynamically. 准备好文档后,元素(#aId)不可用,因此不会分配更改事件,因此我们需要动态绑定更改事件。

You must bind the event handler everytime you render it after the ajax response, in this way (following your example): 每次在ajax响应后呈现它时,都必须以这种方式绑定事件处理程序(以下示例):

$.ajax({
    url: "server.do?button=go&flag=false",
    type: "GET",
    success: function(data) {
        var respContent = "";
        respContent += data;
                    $("#ajaxResponse").show();
        $("#ajaxResponse").html(data);
        // add a event handled for 'change' every time you render it
        $("#aId").change(function(e) {
           var select = $(this);
           console.log('this should work.',select.val());
        });
    }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM