简体   繁体   English

为什么jQuery类不适用于从AJAX响应生成的HTML元素?

[英]Why the jQuery classes are not working for the HTML elements generated from AJAX response?

I'm using PHP, jQuery, Smarty, etc. for my website. 我的网站使用的是PHP,jQuery,Smarty等。 I'm having a HTML form. 我有一个HTML表单。 In this form there is a select control and couple of calendar controls. 在此表单中,有一个选择控件和几个日历控件。 Some classes are added to these controls to achieve some javascript functionality. 一些类被添加到这些控件中以实现某些javascript功能。 When the form loads for the first time the classes applied to these controls work but when I append the same controls with the same classes applied to them, the javascript functionality doesn't work. 第一次加载表单时,应用于这些控件的类将起作用,但是当我将相同的控件附加至具有相同类的控件时,javascript功能将无法正常工作。 Why this is happening and how to resolve this issue? 为什么会发生这种情况,以及如何解决此问题? For your reference I'm putting below the small snippets of codes: HTML Code: 供您参考,我在下面的几小段代码中:HTML代码:

<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_start_date[1]" id="rebate_start_date_1" value="{$data.rebate_start_date}">
<input class="form-control date_control" placeholder="yyyy-mm-dd" type="date" name="rebate_expiry_date[1]" id="rebate_expiry_date_1" value="{$data.rebate_expiry_date}">
<select class="states" multiple="multiple" name="applicable_states[1]" id="applicable_states_1">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>

The AJAX response from PHP file is as follows: 来自PHP文件的AJAX响应如下:

$rebate_no = $_POST['rebate_no'];
 $states = '';
      foreach ($state_list as $key => $value) {
        $states .= "<option value=".$value['id'].">".$value['state_name']."</option>";
      }
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_start_date[$rebate_no]' id='rebate_start_date_$rebate_no' value=''>
<input class='form-control date_control' placeholder='yyyy-mm-dd' type='date' name='rebate_expiry_date[$rebate_no]' id='rebate_expiry_date_$rebate_no' value=''>
<select class='states' multiple='multiple' name='applicable_states[$reabate_no]' id='applicable_states_$reabate_no'>
                    $states    
                    </select>

The actual code is very large. 实际代码非常大。 I've put in only small and necessary part of my code. 我只放入了代码的一小部分和必要的部分。 Would you please help me in this regard please? 您能在这方面帮助我吗? Thanks in advance. 提前致谢。 The jQUery AJAX function code is below: jQUery AJAX功能代码如下:

$(function() {
  $(".add_new_rebate").on("click", function(event) {
    event.preventDefault();
    var manufacturer_id =  $("#company_id").val();

    /*if($.active > 0) { //or $.active      
      request_inprogress();
    } else {*/  
      var next_rebate_no = $('.rebate_block').length + 1;
      var rebate_no      = $('.rebate_block').length + 1;

    if ($('.rebate_block').length>0) { 
      rebate_no = rebate_no+1;
    }

      $('.add_new_rebate').attr('disabled','disabled');
    //}

    $.ajax({
      type: "POST",
      url: "add_rebate_by_product.php",
      data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},  
      beforeSend: function() { 
        $('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
      },
      success: function(data) {
        if(jQuery.trim(data)=="session_time_out") {
        window.location.href = site_url+'admin/login.php?timeout=1';                
        } else {
          $('.rebate_block').append(data);
          $('.add_new_rebate').removeAttr('disabled');
        }
        $('.load').remove();
      }
    });    
 });   
});

because jQuery parses only loaded DOM, it doesn't work with something, that was added to DOM after jQuery processed it. 因为jQuery仅解析加载的DOM,所以它无法处理某些内容,在jQuery处理完之后添加到DOM中。 look at "on" function in jQuery API 看一下jQuery API中的“ on”函数

You Have to add .on if jquery > 1.7 如果jquery> 1.7,则必须添加.on

$('#parent-selector').on('click', 'child-selector', funcion(){})

Child selector is a selector that is just added. 子选择器是刚刚添加的选择器。 You need to add add event in this style for new elements added dynamically on the page Till jquery 1.7 you can you .live('click') 您需要以这种风格添加add事件,以便在页面上动态添加的新元素直到jquery 1.7都可以.live('click')

Like others have mentioned, when you have jquery handlers on present elements they work fine, but the new elements are not binded to those handlers and that's the reason we need to use the .on() method. 就像其他人提到的那样,当您在当前元素上使用jquery处理程序时,它们可以正常工作,但是新元素未绑定到这些处理程序,这就是我们需要使用.on()方法的原因。

So for the newly created elements, we are going to attach a click event handler or any event for that matter as: 因此,对于新创建的元素,我们将附加一个click事件处理程序或与此相关的任何事件,例如:

.states : .states

$(document).on('change','.states',function(){ 
  //on change of select 
});


.date_control : .date_control

$(document).on('click','.date_control',function(){ 
 //on click of input .date_control 
});

DEMO DEMO

I had this problem too, but I found the answer. 我也有这个问题,但是我找到了答案。

Just like I Can Has Kittenz said. 就像我可以让Kittenz说的那样。 You .on() function will do the trick. 您的.on()函数可以解决问题。

On the jQuery website here 在jQuery的网站在这里

Event handlers are bound only to the currently selected elements; 事件处理程序仅绑定到当前选定的元素; they must exist on the page at the time your code makes the call to .on(). 当您的代码调用.on()时,它们必须存在于页面上。 To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. 为了确保元素存在并可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定。 If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. 如果将新HTML注入到页面中,请在将新HTML放入页面后选择元素并附加事件处理程序。 Or, use delegated events to attach an event handler, as described next. 或者,使用委托事件来附加事件处理程序,如下所述。

Which means that if you are calling ajax code (event handlers that weren't there when the code was loaded) you need to bind it to an element that was there. 这意味着,如果要调用ajax代码(加载代码时不存在的事件处理程序),则需要将其绑定到存在的元素。

Here is an example: 这是一个例子:

$( "body" ).on( "click", "p", function() {
    alert( $( this ).text() );
});

You can see that on the link above too. 您也可以在上面的链接中看到它。 There it shows how it works. 在那里显示了它是如何工作的。

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

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