[英]Javascript event triggering creating multiple button .on('click)
我在下面的代碼中使用HTML slim。
.page
.paper
button.button.js-copier I copy things
- content_for :js_includes do
javascript:
var startingHtml = $('.page').html();
function initializePlugin() {
$('.js-copier').each(function () {
$(this).on('click', function () {
$('.page').append(startingHtml);
$(document).trigger('page-refreshed');
});
});
}
// Run it right away
initializePlugin();
$(document).on('page-refreshed', initializePlugin);
有沒有一種方法可以解決以下事實:當我單擊“我復制東西”按鈕時,它會遍歷所選按鈕的所有按鈕,從而創建該按鈕的多個副本?
另外,有沒有更好的方法來編寫此代碼。 我想做的就是只要單擊任何按鈕(第一個按鈕和任何新創建的按鈕)就復制按鈕
安東尼
首先更改:
$('.js-copier').each(function () {
$(this).on('click', function () {
...
對此:
$('.page').on('click', '.js-copier', function () {
...
閱讀此內容以了解https://learn.jquery.com/events/event-delegation/#event-propagation
然后刪除“頁面刷新”事件,因為您不需要它:
$(document).trigger('page-refreshed');
...
$(document).on('page-refreshed', initializePlugin);
演示解決方案:
var startingHtml = $('.page').html(); function initializePlugin() { $('.page').on('click', '.js-copier', function () { $('.page').append(startingHtml); }); } // Run it right away initializePlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="page"> <div class="paper"> <button class="button js-copier"> I copy things</button> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.