你想跟踪你的品牌新的项目?您可以使用自定义事件执行此操作。由于您使用的是jQuery,因此您可以使用方法.trigger()
来创建您的活动。例如,您每次创建元素时都需要触发事件。所以,在你的代码中会添加类似这样:
... // Your code goes here
new_item = '<p class="change-this">'; // The DOM that you will inject
container.append(new_item); // Injecting item into DOM
container.trigger('creation', []); // Firing a event signaling that a new item was created
...
然后,您将创建一个监听这个自定义事件:
container.on('creation', function() {
console.log("Yay! New item added to container!");
});
检查这个片段:
$('#add').on('click', function() {
var item = '<p>New item</p>',
container = $('#container');
container.append(item);
container.trigger('creation');
});
$('#container').on('creation', function() {
var new_message = 'New Item added!<br>';
$('#message').append(new_message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">add</button>
<b id="message"></b>
<div id="container"></div>
请记住,如果您想跟踪e与自定义曲目一起,您只需创建不同的自定义事件并处理其触发器。
就是这样。 jQuery为我们提供了一种简单而美观的方式来处理自定义事件。真棒!
欲了解更多信息,您可以检查这些链接: jQuery.trigger() -
介绍自定义事件 - http://learn.jquery.com/events/introduction-to-custom-events/
自定义事件 - https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
祝您好运!
我认为调用'$ .trigger()'可能是最简单的解决方案。不幸的是,没有可靠的DOM元素创建事件处理程序:http://stackoverflow.com/questions/7434685/event-when-element-added-to-page – 2014-11-23 20:57:38
(也有一些其他有趣的想法在上面的链接,可能对你有帮助。) – 2014-11-23 20:58:39
你可能想阅读[MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)。 – 2014-11-23 21:17:18