简体   繁体   English

Ajax 加载 Function 意外触发多次

[英]Ajax Load Function Firing Multiple Times Unexpectedly

It seems this is a common problem, but I can't seem to get to the root of it my situation.似乎这是一个常见问题,但我似乎无法找到我的情况的根源。 I have a list of items each with an edit button.我有一个项目列表,每个项目都有一个编辑按钮。 Each edit button has a class of edit-button .每个编辑按钮都有一个 class 的edit-button

Below is the code that binds a click event to each button which loads the edit view into an bootstrap popup modal.下面是将点击事件绑定到将编辑视图加载到引导弹出模式中的每个按钮的代码。 My problem is is that it is loading as many modals as edit buttons.我的问题是它加载的模式与编辑按钮一样多。 So if I have three items with edit buttons, it loads that popup three times on top of each other.因此,如果我有三个带有编辑按钮的项目,它会加载该弹出窗口三次。 Also with the debugger, I have concluded that the click event is not being fired six times, but the load function.同样使用调试器,我得出的结论是点击事件没有被触发六次,而是加载 function。

My basic html structure我的基本 html 结构

<!-- List of Items -->
<ul>
    <li>
        <div>Item 1</div>
        <a class="edit-button" href="~/Controllers/Action/1"></a>
    </li>
    <li>
    <li>
        <div>Item 2</div>
        <a class="edit-button" href="~/Controllers/Action/2"></a>
    </li>
    <li>
    <li>
        <div>Item 3</div>
        <a class="edit-button" href="~/Controllers/Action/3"></a>
    </li>
</ul>
<!-- Popup modal container -->
<div class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="ajax-content container-fluid"></div>
        </div>
    </div>
</div>

Ajax function Ajax function

$(".edit-button").each(function () {
    $(this).click(function (event) {
        event.preventDefault();
        $(".ajax-content").load(this.href, function () {
            $(".modal").modal({
                keyboard: true
            }, "show");
        });
    });
});

Try to add stopImmediatePropagation() and IMHO it is better to use a modern unobtrusibe javascript syntax尝试添加 stopImmediatePropagation() 和恕我直言,最好使用现代的 unobtrusibe javascript 语法


<script type="text/javascript">

 $(document).ready(function () {

 $(document).on("click", ".edit-button", (function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
    
       ... your code

 });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM