为什么我在另一个函数中的 jquery post 发送了多次?

Why my jquery post inside another function is sending multiple times?

我在一个简单的 jquery post 中工作。我有一个对象列表,当用户单击列表中的一个对象时,我更改了一些 js 变量以使用此数据发出 post 请求。这是我的 html 代码。

<ul>
    <li data-selected-option="1">
        <a herf="javascript:void(0)" class="option">1</a>
    </li>
    <li data-selected-option="2">
        <a herf="javascript:void(0)" class="option">2</a>
    </li>
    <li data-selected-option="3">
        <a herf="javascript:void(0)" class="option">3</a>
    </li>
</ul>

<div class="modal fade" id="optionmodalsettings" tabindex="-1" role="dialog" aria-labelledby="optionmodalsettings" aria-hidden="true">
    ...
    ...
    <a href="javascript:void(0)" class="send_option_post">Send</a>
    ...
    ...
</div>

这是我的 javascript 代码。

$(function () {
    var post_url ="my_post_url";

    $(".option").on('click', function () {
        $('#optionmodalsettings').modal();
        var selected_option = $(this).closest('li').data('selected-option');

        $('.send_option_post').on('click', function() {
            $.post(update_website_noty_url, {selected_option: selected_option}, function (response) {
                $('#optionmodalsettings').data('modal', null);
                console.log(response);
            });
        });
    });
})

当用户点击列表的一个元素时,我通过 javascript 更改 selected_option var 并打开一个 boostrap 模式。打开 bootstrap 模式后,用户可以点击模式内的按钮 .send_option_post 以发出 post 请求作为参数发送 selected_option 变量。第一次一切正常,但是,如果用户单击另一个元素并发送 post 请求,则 post 会发送两次,如果用户再次单击列表中的一个元素并单击.send_option_post,请求发送3次,必须是点击才post请求。为什么会这样?非常感谢。

每次用户点击 .option,您都会向 .send_option_post 添加另一个点击处理程序。所以如果用户点击 3 个选项,然后点击 .send_option_post,它将 post 3 次。

您应该只绑定一次 .send_option_post 单击处理程序,而不是每次用户单击 .option 时。将 selected_option 变量移动到两个函数的外部范围。

$(function () {
    var post_url ="my_post_url";
    var selected_option;

    $(".option").on('click', function () {
        $('#optionmodalsettings').modal();
        selected_option = $(this).closest('li').data('selected-option');

    });
    $('.send_option_post').on('click', function() {
        if (selected_option === undefined) {
            alert("You need to select an option first");
        } else {
            $.post(update_website_noty_url, {selected_option: selected_option}, function (response) {
                $('#optionmodalsettings').data('modal', null);
                console.log(response);
            });
        }
    });
});