<div>
<ul>
<li><a data-id="1" href="#">Show dialog 1</a></li>
<li><a data-id="2" href="#">Show dialog 2</a></li>
<li><a data-id="3" href="#">Show dialog 3</a></li>
<li><a data-id="4" href="#">Show dialog 4</a></li>
<li><a data-id="5" href="#">Show dialog 5</a></li>
<li><a data-id="6" href="#">Show dialog 6</a></li>
</ul>
</div>
<div class="dialogTest" style="display: none">
<p>Are you shure you want to delete this link?</p>
<p style="margin-top: 15px; text-align: center;"><button>Delete it!</button></p>
</div>
<div class="dialogTestMenu" style="display: none">
<p style="margin-top: 15px; text-align: center;"><a href="#">Delete this link</a></p>
</div>
$(function () {
var ulMenu = function (target) {
console.log('target item',target);
$('.dialogTestMenu').dialog({
title: 'Item #' + target.dataset.id + ' menu',
modal: true,
open: function () {
var rootDialog = this;
$(this).find('a').on('click', function () {
$(rootDialog).dialog('close');
$('.dialogTest').dialog({
title: 'Confirm delete #' + target.dataset.id,
modal: true,
open: function () {
var selfDialog = this;
$(this).find('button').on('click', function () {
console.log('target item to delete',target);
$(target).remove();
$(selfDialog).dialog('close');
return false;
});
},
buttons: {
Cancel: function () {
$(this).dialog('close');
$(rootDialog).dialog('open');
}
}
});
return false;
});
},
buttons: {
Cancel: function () {
$(this).dialog('close');
}
}
});
};
$('ul a').on('click', function () {
ulMenu(this);
return false;
});
});
I have a list of items. Click on item calls dialog with menu . By clicking on menu item Delete this link I get another dialog with confirmation. When I cancel from the second dialog to delete first item (for example), and then I try to delete any other item, it deletes the first, which was cancelled.
Explain me, why do I get an old instance of target, when I try to handle click on button inside the second dialog.
Check out code, fill free to use console.
Because you use
.on()everytime a dialog opens it attach a new click function to buttons. I change your jsFiddle. Check it out. I unbind latest function and then bind new one, btw changed your construction a little bit.