Javascript onclick函数无法正常工作

时间:2019-06-12 09:44:52

标签: javascript jquery laravel sweetalert2

开发需要在使用sweetalert2进行删除之前进行确认的删除功能。 这是我尝试的代码

<button class="btn btn-danger waves-effect" type="button" onclick="book({{ $book->id }})">delete</button>
<form id="delete-form-{{ $book->id }}" action="{{ url('/library/books/', ['id' => $book->id]) }}" method="POST">
    {!! method_field('delete') !!}
    {!! csrf_field() !!}
</form>

这是我在主刀片中推送的JavaScript

<script type="text/javascript">
function book(id) {
    swal({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false,
        reverseButtons: true
    }).then((result) => {
        if (result.value) {
            event.preventDefault();
            document.getElementById('delete-form-'+id).submit();
        } else if (
            // Read more about handling dismissals
            result.dismiss === swal.DismissReason.cancel
        ) {
            swal(
                'Cancelled',
                'Your data is safe :)',
                'error'
            )
        }
    })
}

在主刀片中使用堆栈

@stack('customjs')

单击删除按钮时出现错误。错误是

books:4 Uncaught ReferenceError: book is not defined
at HTMLButtonElement.onclick (books:4)

如何解决此问题并在删除项目之前显示甜蜜提醒?

1 个答案:

答案 0 :(得分:0)

在主刀片的底部或页眉中

@stack('customjs')

在您的刀片中

@push('customjs')
<script type="text/javascript">
    function book()
    {
        //enter code here
    }
</script>
@endpush

您的按钮

<button class="btn btn-danger waves-effect" type="button" onclick="book({{ $book->id }})">delete</button>

如果您使用laravel,则可以适当地使用jQuery wich,使其更容易。

您的按钮

<button class="btn btn-danger waves-effect clickHandleButton" type="button">delete</button>
<form action="{{ url('/library/books/', ['id' => $book->id]) }}" method="POST">
    {!! method_field('delete') !!}
    {!! csrf_field() !!}
</form>

您的javascript

$(document).on('click', '.clickHandleButton', (e) => { //replaces function book()
   $(e.currentTarget).next('form').submit();
   //find the form next to the clicked button and submit the form.
});