简体   繁体   中英

jquery function not getting called on automatically generated html

I am facing a strange issue. My concrete html looks like follows:

<div class="pages">
  <div class="dynamicPages"></div>
  <div class="staticPages">
    <div class="span4">
      <ul class="nav nav-stacked">
        <li>
          <textarea class="newcomment field span12"
            style="width: 350px; height: 20px; resize:none;  font-size: 60%"
            id="newcomment${page.id}"
            name="newcomment${page.id}"
            placeholder="Enter comment here...">
          </textarea>
        </li>
      </ul>
    </div>
  </div>   
</div>

Now sometimes i generate the same html like what is inside the div class span4 and add it to div class dynamic like follows:

  $(".dynamicPages").append(page_html);

this dynamic html i generate after i make a ajax call to the server.

I have the following jquery function when the user enters the enter key in the text area.

  $(".pages").on('keydown','.newcomment',function(event) {
    if(event.which == '13'){
      ... do some stuff
    }
  });

Everything works perfect now.

Now i wanted to the following plugin for my text area:

https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js

So i changed the above jquery like shown below

 $('.pages .newcomment').autogrow().keypress(function(event){
   if(event.which == '13'){
     ...
   }
 });

and in my previous mentioned ajax call in the success event i do something again so autogrow attaches itself to the dynamically generated element as mentioned in this How do I automatically run a method on a dynamically generated textarea with jquery?

$('.pages .newcomment').autogrow();

But now i see in case when i add dynamic html the jquery function is not getting called at all. When i reload the page ie when the html is populated from server side attributes the jquery function is called properly.

$('.pages .newcomment').autogrow().keypress(function(event){

This line is equivalent to this:

$('.pages .newcomment').autogrow();
$('.pages .newcomment').keypress(function(event){

This won't work on dynamically-added elements, because they don't exist at the time of the bind. You do event delegation with on earlier in your code. You need to do it again, and abandon your attempt at chaining:

$('.pages .newcomment').autogrow();
$(".pages").on('keydown','.newcomment',function(event) {

Use delegate() instead of on() .

.delegate()

Attach a handler to one or more events for all elements that match the selector, now or in the future , based on a specific set of root elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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