你想跟蹤你的品牌新的項目?您可以使用自定義事件執行此操作。由於您使用的是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