动态添加的div在被调用时将不起作用

时间:2013-02-22 17:34:41

标签: javascript jquery

我正在尝试创建一个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 个答案:

答案 0 :(得分:3)

更改您的

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

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

它被称为delegated event

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

改变:

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

用这个:

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

答案 3 :(得分:0)

试试这个:

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

在这种情况下,event delegation to existing closest parent

时需要dom was ready.