HTML elements generated by Javascript - now not fu

2019-07-18 13:42发布

问题:

This question already has an answer here:

  • Event binding on dynamically created elements? 23 answers

I am generating HTML elements using javascript. I applied the same class to all elements. I have a function that will execute when that class experiences the keyup event.

The problem is that my function is not recognizing the elements that javascript created.

See the example here --> jsFiddle

HTML

<p>Type in the box below, an alert will appear</p>
   <input type='text' id='x' size='30' class='conv'/>
   <br/><br/>

   <button id='btn'>Now Click Me</button><br/><br/>

   <div id='mainform'></div>

jQuery

$(document).ready(function() {
    $('button').click(function() {
      var a =  "<p>The boxes below have the same class, thus they should show the alert when you type</p><input type='text' size='30' class='conv' id='a0'/><br/>";
      var b = "<input type='text' size='30' class='conv' id='a1'/><br/>";
      $('#mainform').append(a + b);       
    });

    $('.conv').keyup(function() {
       alert('it works'); 
    });

});

回答1:

Use event delegation (As .conv being added dynamically)

$('#mainform').on('keyup','.conv',function() {
     alert('it works'); 
});

Demo ---> http://jsfiddle.net/VxTh5/7/

  • http://learn.jquery.com/events/event-delegation/


回答2:

Since the class is added dynamically, you need to use event delegation to register the event handler

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#mainform').on('keyup', '.conv', function(event) {
    event.preventDefault();
    alert('it works');
});

This will attach your event to any input within the #mainform element, reducing the scope of having to check the whole document element tree and increasing efficiency.



回答3:

Do event delegation.

$(document).on('keyup' ,'.conv',function() {
       alert('it works'); 
    });

http://api.jquery.com/on/



回答4:

The reason it's not working is because your element doesn't exist at DOM ready, therefore when your handler is called, it doesn't find these elements. Event delegation binds the click event to an element that exists:

$("#mainform").on('keyup', '.conv', (function() {
   alert('it works'); 
});

We use #mainform since it exists at DOM ready. You can also use document, however, it is a very broad click handler.



回答5:

you need to bind event after appending created div, hence move your binding code inside button click event

$(document).ready(function() {
    $('button').click(function() {
      var a =  "<p>The boxes below have the same class, thus they should show the alert when you type</p><input type='text' size='30' class='conv' id='a0'/><br/>";
      var b = "<input type='text' size='30' class='conv' id='a1'/><br/>";
      $('#mainform').append(a + b);
       $('.conv').keyup(function() {
          alert('it works'); 
       });

    });
});