2017-04-20 46 views
0

我有一個父div與編號test-container和這裏面是子類icon-btn元素點擊vs文檔點擊首選項

當我點擊parent-div中的任何位置時,新的child-div元素被添加到位於click處的parent-div。

問題是當我點擊child-div元素parent-div事件先觸發然後觸發child-div事件。我希望孩子事件先發射。

JS:

$('#test-container').on('click', function(e) { 
    alert('clicked'); 
    var parentOffset = $(this).offset(); 
    var relX = e.pageY - parentOffset.top; 
    var relY = e.pageX - parentOffset.left; 
    $(this).append('<div class="icon-btn" style="top: ' + relX + 'px; left: ' + relY + 'px; display: block; position: absolute; border-radius: 3px; border: 1px solid #ffffff; overflow: visible; box-shadow: 0 0 2px #000; z-index: 16; width: 50px; height: 50px; padding: 15px 14px; color: #fff; cursor: pointer;" id="icon-btn-1"></div>') 
});; 

$(document).ready(function() { 
    $(document).on('click', '.icon-btn', function() { 
    alert('clicked sub div'); 
    }); 
}); 

HTML:

<div style="width: 300px; position: relative;"> 
    <img src="http://www.flowermeaning.com/flower-pics/Daffodil-Meaning.jpg" class="img-responsive" width="100%" height="100%"> 
    <div id="test-container" style="position: absolute; top: 0px; cursor: crosshair; left: 0px; width: 300px; height: 200px; z-index: 8;"> 
    <div class="icon-btn" style="top: 45px; left: 184px; display: block; position: absolute; border-radius: 3px; border: 1px solid #ffffff; overflow: visible; box-shadow: 0 0 2px #000; z-index: 16; width: 50px; height: 50px; padding: 15px 14px; color: #fff; cursor: pointer;" 
id="icon-btn-1"></div> 
    </div> 
</div> 

請參閱JSFiddle的工作示例。

+0

綁定試試這個:$(文件)。在( '點擊',' #test-container',函數(e){ $('#test-container')。on('click',function(e){ https://jsfiddle.net/x95owvL8/8/ – kag

+0

@kag是的工作的實例。發佈它作爲答案。 – abhig10

回答

0

// $(」 #測試容器 ')上(' 點擊 '功能(E){// 這是所有關於元素的

$(document).on('click','#test-container', function(e) { 
    alert('parent div'); 
    var parentOffset = $(this).offset(); 
    var relX = e.pageY - parentOffset.top; 
    var relY = e.pageX - parentOffset.left; 
    $(this).append('<div class="icon-btn" style="top: ' + relX + 'px; left: ' + relY + 'px; display: block; position: absolute; border-radius: 3px; border: 1px solid #ffffff; overflow: visible; box-shadow: 0 0 2px #000; z-index: 16; width: 50px; height: 50px; padding: 15px 14px; color: #fff; cursor: pointer;" id="icon-btn-1"></div>') 
});; 

$(document).ready(function() { 
    $(document).on('click', '.icon-btn', function() { 
    alert('child sub div'); 
    }); 
}); 
1

Document click也可用於動態添加該類的元素。

Element click僅適用於在裝載後準備好的元件。如果您將使用該選擇器添加元素,則element click將不適用於它們。

+0

我明白這一點。但我想要的是'文檔點擊'應該在'元素點擊'之前觸發。 – abhig10

0

將新元素附加到父項時,附加到該元素的先前事件將不適用於新元素。 你根本就再次刪除以前,並附上相同的事件,以收到預期的效果

$('.selectorOfYourDynamicChild').off("click").on('click', function(e) { 
     // Your logic goes here 
    }) 
0

更改您連接點擊事件上的div孩子,喜歡的方式:

`$(document).ready(function() { 
    $('.icon-btn').on("click", function() { 
    alert("child sub div"); 
    }); 
});`