由Javascript生成的HTML元素 - 现在无法正常工作 [英] HTML elements generated by Javascript - now not functional

查看:99
本文介绍了由Javascript生成的HTML元素 - 现在无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javascript生成HTML元素。我对所有元素应用相同的类。我有一个函数,将在该类遇到keyup事件时执行。

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.

问题是我的函数不能识别javascript创建的元素。

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

查看此处的示例 - > jsFiddle

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

});


推荐答案

使用事件委托( As .conv 动态添加

Use event delegation (As .conv being added dynamically)

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

演示 ---> http://jsfiddle.net/VxTh5/7/

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

这篇关于由Javascript生成的HTML元素 - 现在无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆