简体   繁体   中英

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 .

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.

My basic html structure

<!-- 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

$(".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


<script type="text/javascript">

 $(document).ready(function () {

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

 });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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