您想跟踪您的全新商品吗?您可以使用自定义事件来执行此操作。由于您使用的是 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>
请记住,如果您想使用自定义轨道跟踪元素,您只需要创建不同的自定义事件并处理其触发器。
就是这样了。jQuery 为我们提供了一种简单而美观的方式来处理自定义事件。惊人的!
有关更多信息,您可以查看以下链接:jQuery.trigger() -
http://api.jquery.com/trigger/
介绍自定义事件 -
http://learn.jquery.com/events/introduction-to-custom-events/
CustomEvent -
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
祝你好运!