如何修复 "data("url") is undefined" Jquery 中的问题?
How to fix "data("url") is undefined" issue in Jquery?
数据("url") return未定义
$(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;
}
})
})
})
<button data-url="<?php echo base_url("product/deleteProduct/$product->id"); ?>" class="btn btn-outline btn-danger removeBtn">Remove</button>
显然 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”,因此此代码段将只打印值,例如“某事”到控制台
数据("url") return未定义
$(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;
}
})
})
})
<button data-url="<?php echo base_url("product/deleteProduct/$product->id"); ?>" class="btn btn-outline btn-danger removeBtn">Remove</button>
显然 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”,因此此代码段将只打印值,例如“某事”到控制台