【发布时间】:2015-09-19 11:24:28
【问题描述】:
我打算使用 Bootstrap Popover 模块作为删除事件的确认,这样当点击 <button> 时,它不会简单地触发一个函数,它会打开一个弹出窗口,让用户确认 或关闭该操作。
需要注意上下文环境是一个自建的单页~mvc webapp,其中元素是动态添加的(因此我事先不知道元素的数量,也不能硬编码每个元素的动作)
在当前情况下(没有弹出框)我做了类似的事情来触发直接(不符合)动作:
$view.on('click', '.deleteButton', function () {
var id = $(this).attr('data-id');
api.delete('someUrl' + id, successFunction);
}):
按钮的标记类似于此:
<button class="deleteButton" data-id="2">Delete me!</button>
但是,现在我想添加一个确认步骤(例如“您确定要删除这个宏伟的按钮吗?(Y/N)”),并考虑使用引导弹出窗口。
经过一番头脑风暴后,我想出了一个类似以下的策略。这不是最佳解决方案(最佳解决方案是扩展弹出框模块,以便我能够将 ConfirmFunction 和 cancelFunction 传递给弹出框)。
首先,我必须启动弹出框。
$view.find('.deleteButton').popover({
title: 'Are you sure?', //Example title
html: true, //Essential for the html to work as expected
selector: '.deleteButton', //Allow ajaxing in of new elements
container: '.viewName', //So that the popovers reside w/in the current view and thus can be bound to $view (a jQuery object for the view)
content: [...], //Two <button>s with a specified class, e.g. .viewName__deleteButton--popover
});
其次,我会将一个事件绑定到弹出框内的按钮
$view.on('click', '.viewName__deleteButton--popover', function () {
var id = ??; // Here comes the troubling part - how do I get the ID of the clicked button? How can I target the original button? If I can do that, I think it would solve everything.
api.delete('someUrl' + id, successFunction);
});
出现的问题是如何定位最初点击的按钮?
我唯一能想到的,一点也不整洁的灵魂是做这样的事情:
var popoverId = $(this).parents('.popover').attr('id'); //returns popoverXXXXXX
var parentElement = $view.find('[aria-describedBy="' + popoverId + '"]');
它有效,但它是一个非常肮脏的解决方案,一点也不“好”。
有什么方法可以更简洁地完成吗?最好我可以定义一个通用函数,例如$element.confirmationPopover({popoverSettings...}, confirmationFunction, declineFunction);,它可以在多种情况下使用。
(PS:我想不出这个Q的简洁标题,一如既往地感谢您的建议!)
【问题讨论】:
标签: javascript jquery twitter-bootstrap twitter-bootstrap-3 popover