相关疑难解决方法(0)

jQuery如何绑定onclick事件以动态添加HTML元素

我想将onclick事件绑定到我使用jQuery动态插入的元素

但它永远不会运行绑定功能.如果你能指出为什么这个例子不起作用以及如何让它正常运行,我会很高兴:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
        <head>
          <title>test of click binding</title>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
          <script type="text/javascript">


        jQuery(function(){
          close_link = $('<a class="" href="#">Click here to see an alert</a>');
          close_link.bind("click", function(){
            alert('hello from binded function call');
            //do stuff here...
          });
  
          $('.add_to_this').append(close_link);
        });
          </script>
        </head>
        <body>
          <h1 >Test of click binding</h1>
          <p>problem: to bind a click event to an element I append via JQuery.</p>

          <div class="add_to_this">
            <p>The link is created, then added here below:</p>
          </div>

          <div …
Run Code Online (Sandbox Code Playgroud)

javascript jquery bind

123
推荐指数
4
解决办法
24万
查看次数

由动态生成的元素触发的事件不会被事件处理程序捕获

我有一个<div>使用id="modal"jQuery load()方法动态生成的:

$('#modal').load('handlers/word.edit.php');
Run Code Online (Sandbox Code Playgroud)

word.edit.php包含一些输入元素,它们被加载到一个模态中<div>.

使用jQuery的keyup方法我可以在事件触发后捕获输入值,但是当元素被动态添加到模态div时,当用户输入文本时,事件不会激活.

哪个jQuery方法支持处理由动态创建的元素触发的事件?

用于创建新输入元素的代码是:

$('#add').click(function() {
    $('<input id="'+i+'" type="text" name="translations' + i + '"  />')
      .appendTo('#modal');
Run Code Online (Sandbox Code Playgroud)

捕获用户值的代码是:

$('input').keyup(function() {
    handler = $(this).val();
    name = $(this).attr('name');
Run Code Online (Sandbox Code Playgroud)

第二个代码块似乎适用于原始元素,但新动态生成的元素不会触发它.

javascript jquery

51
推荐指数
2
解决办法
2万
查看次数

标签 统计

javascript ×2

jquery ×2

bind ×1