JQuery:动态更新HTML,以便JQuery

时间:2017-04-30 21:01:17

标签: javascript jquery html

所以,首先,我是Web的新手(html / js)

我想要实现的目标:

  1. 我有一个自定义,我希望能够动态(使用jquery)为该树创建子项:
  2. HTML:

        <ul>
          <li>
            Item
            <input type="button" value="+" class="childAdder">
            <ul class="childrenList"></ul>
          </li>
        </ul>
    

    JS:

    $(".childAdder").click(function() { // add child which is the same as root
      $(this).parent().children(".childrenList").append(
        '<li>Item</li>\
         <input type="button" value="+" class="childAdder">\
         <ul class="childrenList"></ul>'
      );
    });
    
    1. 正如你所看到的,我知道如何添加一个孩子(或多或少,建议总是受欢迎)。但是,问题是,此代码仅适用于“预定义”的项目 - &gt;每次我动态地(通过JS)添加一个孩子,这个代码只是不执行这个新创建的元素(尝试alert('Hello'); - 没有看到任何东西)
    2. 问题: 我假设我需要以某种方式“正确地”将我的新孩子添加到HTML或其他任何东西的DOM(?)中,以便JS能够识别它,对吧? (但这似乎只能通过HTML静态页面实现,不是吗?)

      无论如何,我如何使这个东西工作:添加新的子代,以便为JS创建的元素执行为HTML元素执行的相同JS代码

      • 是否有解决方案或整个实施只是错误

1 个答案:

答案 0 :(得分:3)

您需要使用 event delegation 才能生效。这是通过使用on JQuery方法进行事件连接和修改参数来完成的。

另外(FYI),<ul>元素只能包含<li>个元素作为子元素。您的项目符号/嵌套列表结构无效。

最后,在您添加的HTML字符串中包含随机\字符,这些字符不需要,并且在这些位置实际上无效。

这是正确的实现,HTML已更正为有效。

// JQuery event delegation requires the use of the "on" method and then you 
// bind the event to an object that is sure to always recieve the event (document 
// works well here because of event bubbling). Then you specify the target element
// that the actual event will be triggered from.
$(document).on("click", ".childAdder" ,function() { 
  // add child which is the same as root
  $(this).parent().children(".childrenList").append("<li>Item<br><input type='button' value='+' class='childAdder'><ul class='childrenList'></ul></li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
      <!-- <ul> and <ol> elements can only have <li> elements as thier children (aside from
           comments like this one). To properly nest lists, organize the HTML as follows: -->
      <li>Item<br>
        <input type="button" value="+" class="childAdder">
        <ul class="childrenList"></ul>
      </li>
 </ul>