2016-08-05 10 views
1

特定の要素がビューにバインドされた後にイベントを発生させようとしています。jQuery - 動的に追加された要素の読み込み

私は、次を使用しようとしているが、それは動作しません:

$(".featWrap").on("load", ".box", function() { 
    $(".featWrap").slick({dots: true}); 
}); 

を、次の作品を使用して、私は要素がバインドされたときにイベントを発生する必要があり、そのクリックされていないとき:

$(".featWrap").on("click", ".box", function() { 
    $(".featWrap").slick({dots: true}); 
}); 

私はそのバインドさの後にカスタムイベントを使用して考えていたが、データをバインドする機能は、次のようになりますので、私はそうすることはできません。

APP.bind["game.featuredPrizes"] = APP.get("user.featuredPrizes", function (featuredPrizes) { 
    return featuredPrizes.map(formatFeatured); 
}); 
+0

bytheway '.load()'はjquery ver 1.8で廃止され、3.0から削除されました。 – bipen

+0

@FerVargas add html plz –

答えて

2

新しい追加機能を追加するには、Mutation eventsを使用します。ここにはdocuments browser support for mutation eventsがあります。

少しデモ:

// listen for the newly added elements with class box 
 
$(document).on('DOMNodeInserted', '.box', function (e) { 
 
    var element = e.target; 
 
    setTimeout(function() { 
 
    $(element).fadeOut(1000, function() { 
 
     $(this).remove(); 
 
    }); 
 
    }, 2000); 
 
}); 
 

 
$(function() { 
 
    
 
    // create and add a new element on the fly 
 
    
 
    $('#insert').on('click', function (e) { 
 
    $('<div/>', { 
 
     class: 'test', 
 
     text: 'Test Generic' 
 
    }).appendTo('body'); 
 
    }); 
 
    
 
    $('#insertBox').on('click', function (e) { 
 
    $('<div/>', { 
 
     class: 'box', 
 
     text: 'Test Generic' 
 
    }).appendTo('body'); 
 
    }); 
 

 
});
.box { 
 
    padding: 1em; 
 
    background: #ffa; 
 
    border: 1px solid #999; 
 
} 
 
.test { 
 
    padding: 1em; 
 
    background: #008000; 
 
    border: 1px solid #999; 
 
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 

 
<button id="insertBox">Insert box</button> 
 
<button id="insert">Insert a generic element</button>

+0

これはトリックを行い、要素がいつ追加されるかを検出します。今問題は、滑らかな初期化されていないことです..しかし、これはこれとは無関係です。 –

0

私はそのクリックしたときに、要素がバインドされたときにイベントを発生する必要はありません。

これにはありません可能なようです

$("#id").on("bind", function() { 
    // This is what you want to achieve 
    // Calling this function when an event has been binded to $("#id") 
    console.log("bind click binded"); 
}); 

$("#id").bind("click", function() { 
    console.log("click binded"); 
}); 
関連する問題