所以,首先,我是Web的新手(html / js)
我想要实现的目标:
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>'
);
});
alert('Hello');
- 没有看到任何东西)问题: 我假设我需要以某种方式“正确地”将我的新孩子添加到HTML或其他任何东西的DOM(?)中,以便JS能够识别它,对吧? (但这似乎只能通过HTML静态页面实现,不是吗?)
无论如何,我如何使这个东西工作:添加新的子代,以便为JS创建的元素执行为HTML元素执行的相同JS代码
答案 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>