为什么可以';t jQuery parents()查找我的元素?
我就是无法让这个(相当简单)函数正常工作,parents()似乎无法找到我想要的div并将其淡出:( HTML为什么可以';t jQuery parents()查找我的元素?,jquery,jquery-selectors,parent-child,Jquery,Jquery Selectors,Parent Child,我就是无法让这个(相当简单)函数正常工作,parents()似乎无法找到我想要的div并将其淡出:( HTML 我尝试了$(this).parents(.photo”).fadeOut('fast');和$(this.cloest('div.photo”).fadeOut('fast');,但没有任何连接:(这是一个范围问题。在ajax的success回调中,这个并不是指您认为它做了什么,而是指函数本身 您应该在ajax调用之外缓存$(this)的副本,并使用该副本: $('.del
我尝试了
$(this).parents(.photo”).fadeOut('fast');
和$(this.cloest('div.photo”).fadeOut('fast');
,但没有任何连接:(这是一个范围问题。在ajax的success
回调中,这个
并不是指您认为它做了什么,而是指函数本身
您应该在ajax调用之外缓存$(this)
的副本,并使用该副本:
$('.deleteButton').click( function() {
var $img = $(this);
//....//
$.ajax({
url: 'scripts/deletePhoto.php',
data: 'img='+img,
type: 'POST',
mode: 'abort',
success: function(){
$img.parents("div.photo").fadeOut('fast');
}
});
// ... //
}
您需要缓存当前事件并使用这些变量。这是一个范围问题
var currObj=$(this); cache the current event and use those variable.
$('.deleteButton').click( function() {
var $currObj=$(this); // cache the current event.
var img = currObj.attr('href');
img = "../"+img;
var answer = confirm('Are you sure you want to delete this item? (This cannot be undone!)');
if (answer) {
$.ajax({
url: 'scripts/deletePhoto.php',
data: 'img='+img,
type: 'POST',
mode: 'abort',
success: function(){
$currObj.parents("div.photo").fadeOut('fast');
}
});
}
return false;
});
找不到对象的原因是
$(此)
没有指向您认为它指向的对象。
您正在Ajax调用的回调函数中使用它,该调用的上下文与click事件处理程序不同
在进行Ajax调用之前,将其插入一个变量,这样您就可以:
$('.deleteButton').click( function() {
var img = $(this).attr('href');
img = "../"+img;
var answer = confirm('Are you sure you want to delete this item? (This cannot be undone!)');
if (answer) {
var my_item = $(this);
$.ajax({
url: 'scripts/deletePhoto.php',
data: 'img='+img,
type: 'POST',
mode: 'abort',
success: function(){
my_item .parents("div.photo").fadeOut('fast');
}
});
}
return false;
});
在click处理程序中,您必须保留对按下按钮的引用,否则,
此
将在AJAX成功处理程序中被“覆盖”:
$('.deleteButton').click( function() {
var img = $(this).attr('href'),
$self = $(this);
img = "../"+img;
$self.parents("div.photo").fadeOut('fast');
然后,在成功处理程序中:
$('.deleteButton').click( function() {
var img = $(this).attr('href'),
$self = $(this);
img = "../"+img;
$self.parents("div.photo").fadeOut('fast');
顺便说一句,我建议在$调用中进行此更改。ajax
调用:
data: 'img=' + encodeURIComponent(img),
这可以避免向服务器端脚本发送格式错误的查询字符串。$(这)将用于ajax功能。而不是单击手柄在您的示例中,
currObj
已经是一个jQuery对象,因此无需再次将其包装在$()
中!一个好的约定是将$用于jQuery对象:var$currObj=$(这是);不确定是否要将$放在变量前面?这不会影响jQuery吗?@DjangoReinhardt-不,这完全是有意为之。许多jQuery开发人员习惯在变量名前面加上$
前缀,当它引用jQuery对象时。这会阻止您对变量进行双重包装。不,这不会干扰jQ谢谢你的解释!