所以,首先,我是 Web (html/js) 的新手
我想要实现的目标:
- 我有一个自定义树,我希望能够动态(使用 jquery)为该树创建子树:
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>'
);
});
- 正如您所看到的,我知道如何添加一个 child (或多或少,总是欢迎建议)。然而,问题是,此代码仅适用于 html 中“预定义”的项目 --> 每次我动态地(通过 JS )添加一个子元素,此代码只是不执行这个新创建的元素(尝试执行
alert('Hello');
- 什么也没看到)
问题: 我假设我需要以某种方式“正确”地将我的新 child 添加到 HTML 或其他内容的 DOM(?) 中,以便 JS 识别它,对吗? (但这似乎只能通过 HTML 静态页面来实现,不是吗?)
无论如何,我该如何让这件事发挥作用:添加新的子元素,以便为 JS 创建的元素执行为 HTML 元素执行的相同 JS 代码
- 是否有解决方案或者整个实现只是错误?
最佳答案
您需要使用event delegation 才能实现这一点。这是通过使用 on
来完成的用于事件连接和修改参数的 JQuery 方法。
另外(仅供引用),a <ul>
元素只能包含 <li>
作为 child 的元素。您的项目符号/嵌套列表结构无效。
最后,在您附加的 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>
关于javascript - JQuery:动态更新 HTML,以便 JQuery 识别它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711278/