我们有代码将html加载到具有类内容的div。我们有div元素和链接类,它具有data-href和一些其他data- *属性。代码如下:
$(document).on('click', '.link', linkClick);
linkClick: function (event) {
event.stopPropagation();
$('.content').load($(this).data('href'), function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
我想在load函数的回调中访问$(this)来获取所有其他数据的值 - 点击链接的*属性,我该怎么做?
答案 0 :(得分:2)
在加载调用之前创建对它的作用域引用:
function (event) {
event.stopPropagation();
var $that = $(this); // <- Like this
$('.content').load($(this).data('href'), function (response, status) {
// You can use $that here
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
答案 1 :(得分:0)
$(document).on('click', '.link', linkClick);
var href = $(this).data('href');
linkClick: function (event) {
event.stopPropagation();
$('.content').load(href, function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}
答案 2 :(得分:0)
您可以使用event.target
来访问点击的元素。最常见的方法是将其存储在 或 self 变量下。
$(document).on('click', '.link', linkClick);
linkClick = function (event) {
event.stopPropagation();
var that = event.target;
$('.content').load($(that).data('href'), function (response, status) {
if (status == 'error') {
$('.content').html("Something went wrong. Please try again later");
}
});
}