【问题标题】:using jQuery $(this) within Bootstrap modal to refer to modal target在 Bootstrap 模态中使用 jQuery $(this) 来引用模态目标
【发布时间】:2018-01-24 20:15:06
【问题描述】:

我有一个动态数量的带有.btn-trash. 类的按钮,我使用$(this) 根据它们在dom 中的位置在单击这些按钮中的任何一个时执行一些代码。我想修改它以在单击同一按钮时打开一个 Bootstrap 确认模式窗口,并在确认此模式时执行相同的代码。我不能再使用$(this),因为我不在dom 中.btn-trash 的上下文中,而是在我的模态中新的确认按钮的上下文中。我现在无法确定单击了哪个.btn-trash,以便执行我的逻辑。有没有办法做到这一点?谢谢。

标记:

<button class="btn btn-primary btnblue btn-trash" data-toggle="modal" data-target="#delete-modal">
    <span class="glyphicon icon-trash"></span>
</button>

<div class="modal fade" id="delete-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Are you sure?</h4>
            </div>
            <div class="modal-body">
                <p>text</p>
            </div>
            <div class="modal-footer text-left">
                <a class="btn btn-secondary btn-delete-plan" data-dismiss="modal">Ok</a>
                <a class="btn btn-default" data-dismiss="modal">Cancel</a>
            </div>
        </div>
    </div>
</div>

脚本:

$(document).on('click', '.btn-trash', function () {
    //moved initial logic from here to '.btn-delete-plan' click
});

$(document).on('click', '.btn-delete-plan', function () {
    //target the '.btn-trash' that was initially clicked and execute code
    //based on its position in the dom
});

【问题讨论】:

  • 保存参考var me = $(this)

标签: jquery html bootstrap-modal


【解决方案1】:

正如@Jasen 所说,只需在您的 .btn-trash 点击处理程序中保存一个引用即可。

var $lastClicked; 
$(document).on('click', '.btn-trash', function () {
    $lastClicked = $(this);
});

$(document).on('click', '.btn-delete-plan', function () {
    //use $lastClicked
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2019-08-08
    • 2018-12-13
    • 1970-01-01
    • 2016-08-26
    • 2018-08-10
    • 2021-11-10
    相关资源
    最近更新 更多