2

我正在尝试创建一个 div 列表。单击新图层按钮时,会创建一个具有唯一 ID 的新 div。当我尝试调用这些动态添加的 div 时,没有响应。我很困惑,因为预先存在的 div 有效。

<input type="submit" id="newLayer" value="New Layer">

 <div id="layersContainer" class="layerscontainer">
    <div class="layer" id="layer1">fadfa</div>
    <div class="layer" id="layer2">2</div>            
 </div>


var newLayerCounter = 2;
var layerID = "";
var layersArray = new Array();
var clickedElement = "";


function selectLayer(){

      $(clickedElement).css({"background-color":"yellow"});

    }

$('#layersContainer div').on("click", function(){

    clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();

});

$('#newLayer').on("click", function(){

    newLayerCounter = newLayerCounter + 1;
    layerID = "#layer"+ newLayerCounter;

    $('<div/>', {
    id: "layer"+ newLayerCounter,
    class: "layer"
   }).appendTo('#layersContainer');

    $(layerID).text('hey');

})

这是一个工作 JSfiddle 的链接

http://jsfiddle.net/Q3dSp/24/

4

4 回答 4

3

改变你的

$('#layersContainer div').on("click", function(){

$(document).on("click", '#layersContainer div', function () {
    clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();
});

它被称为委托事件

于 2013-02-22T17:39:05.150 回答
0

Try with this one:

 $('#layersContainer').on("click", 'div', function(){
clickedElement = $(this).attr("id");
    alert(clickedElement);
    selectLayer();
 });

In this situation you need a event delegation to existing closest parent when dom was ready.

于 2013-02-22T17:40:56.863 回答
0

尝试$('#layersContainer').on("click", "div", function(){ (...) });

http://jsfiddle.net/3hqfn/1/

于 2013-02-22T17:38:05.080 回答
0

改变 :

$('#layersContainer div').on("click", function(){

有了这个:

$('#layersContainer').on("click", "div", function(){
于 2013-02-22T17:38:17.647 回答