HTML elements generated by Javascript - now not fu

2019-07-18 13:03发布

This question already has an answer here:

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'); 
    });

});

5条回答
Summer. ? 凉城
2楼-- · 2019-07-18 13:47

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楼-- · 2019-07-18 13:50

Do event delegation.

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

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

查看更多
Root(大扎)
4楼-- · 2019-07-18 13:51

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'); 
       });

    });
});
查看更多
Summer. ? 凉城
5楼-- · 2019-07-18 13:58

Use event delegation (As .conv being added dynamically)

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

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

查看更多
趁早两清
6楼-- · 2019-07-18 14:02

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.

查看更多
登录 后发表回答