如何解决“数据(“ URL”)未定义”在jQuery中的问题?

时间:2019-06-11 18:35:00

标签: jquery undefined sweetalert2

data(“ url”)返回未定义

> C:\Users\erik\AppData\Local\Android\Sdk\tools\bin\sdkmanager.bat --licenses 
$(document).ready(() => {
    $(".removeBtn").click((e) => {

        var $data_url = $(this).data("url");

        console.log($data_url); //It return undefined

        Swal.fire({
            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!'
        }).then((result) => {
            if (result.value) {
                window.location.href = $data_url;
            }
        })
    })
})

1 个答案:

答案 0 :(得分:0)

显然this并未引用您认为的元素。

(这归因于箭头功能,其作用域不为this

相反,您应该在此处使用e.target来获取被点击的元素

$(document).ready(() =>{ $(".removeBtn").click((e) =>{

    var $data_url = $(e.target).data("url");

    console.log($data_url); //It return undefined

})

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-url="something" class="btn btn-outline btn-danger removeBtn">Remove</button>

注意:data-url的值是“ something ”,因此此代码段只会打印例如“ 某物”到控制台