简体   繁体   中英

Javascript onclick: only works once

Here is the method I call, where I delete the event by id:

function delete_event(id)
{
    $.ajax({
        url: "/delete/"+id,
        type: "post",
        data: {  '_token': '{{csrf_token()}}' },
        success: function(data) {
            if (data.success == 1)
            {
                $("#alert").addClass("alert alert-success");
                $("#alert").innerText = "it worked";
                $("#alert").remove();
                $("alert").fadeOut(3000);
            }
            else
            {
                $("#alert").addClass("alert alert-danger");
                $("#alert").text("it didn't work");
                $("#alert").delay(3000).fadeOut(1000);
            }
        },
        error: function(data)
        {
            console.log("neieieiin");
            console.log(data);
        },
        complete: function(){}
    })
}

Here is the HTML-Code:

<div id="alert">
</div>

<table class="table table-striped">
    <tr>
        <th>Event Name</th>
        <th>Starting Date</th>
        <th>Location</th>
        <th>Actions</th>
    </tr>

    @foreach($events as $event)
        <tr id="{{$event->event_id}}">
            <td>{{$event->event_name }}</td>
            <td>{{$event->start_date}}</td>
            <td>{{$event->street_address}}</td>
            <td>
                <a>
                    <button onclick="delete_event({{$event->event_id}})" type="button" class="btn btn-default">
                    <i class="fa fa-times" aria-hidden="true"></i>
                    </button>
                </a>
            </td>
        </tr>
    @endforeach

</table>
@endsection

When I click the delete button it only once shows it worked/it didn't work. If I click it a second time nothing happens any suggestions?

You can use jquery on click method to solve this:

Change:

<button data-id="{{$event->event_id}}" type="button" class="btn btn-default delete_button">


jQuery(document).on("click",".delete_button",function(){

    var id = $(this).data("id");

    $.ajax({

        url: "/delete/"+id,
        type: "post",
        data: {  '_token'           : '{{csrf_token()}}' },
        success: function(data) {
            if(data.success == 1)
            {
                //do as you want
            }

        },

    });

});
$("#alert").fadeIn();
$("#alert").addClass("alert alert-danger");
$("#alert").text("it didn't work");
$("#alert").delay(3000).fadeOut(1000);

All I had to do is to fadeIn() the Element again. :D

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