简体   繁体   中英

jQuery on click event firing multiple times

I just learned how to use the method .on() and I use it to add an event handler to some buttons that are added "live" (after the DOM is ready).

$('#table').on("click", ".delete", function() {
    //whatever
});

This seems to work fine but when I use it in my code I get the click event fired twice. It fires as many times as I have changed the selector, that is, I click a name in the selector and then another and another, let's say 3 times, then when clicking the mentioned button I will get an alert with all those 3 names instead of only the one is selected at that time.

I haven't been able to replicate it in a JsFiddle as the whole thing is quite big. So let me know what else I can add to make the question better.

JS

 $('#dataSelector').change(function() {
   #more code
    $('#table').on("click", ".delete", function() {
        var data_name = $("#dataSelector option:selected").attr('name');
        alert(data_name);
    });
  });

HTML

<div id="selectData">
    <label>Select:</label>
    <br>
    <div class="">

        <select id="dataSelector" class="form-control">

            <option id="default" selected="true" name="default">Pick</option>

            <option value="1" name="somethingA">somethingA</option>

            <option value="2" name="somethingB">somethingB</option>

            <option value="3" name="somethingC">somethingC</option>

        </select>


    </div>
</div>

<div id="goal_table" class="col-md-12">

    <table id="table" class="table table-bordered">
        <tbody>
            <tr>
                <th>Name1</th>
                <th>Name2</th>
                <th>Name3</th>
                <th>name4</th>
                <th></th>
            </tr>
            <tr id="13">
                <td>somethingA</td>
                <td>value</td>
                <td>whatever</td>
                <td>∞</td>
                <td>
                    <button name="13" type="button" class="btn btn-default delete"><i class="fa fa-trash" aria-hidden="true"></i>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>

</div>

just add off() before on() to remove existing event on it

there's a possibility that you already bind an event in that element so if you want to rebind the event you just off('event') to avoid firing event multiple times

$('#table').off("click").on("click", ".delete", function() {
    var data_name = $("#dataSelector option:selected").attr('name');
    alert(data_name);
});

I tested your code, for me its working fine. may be in code you give same id for selector and delete button. please check and give unique name to each of your objects.

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