JQuery - 获取更高级别项的属性

时间:2012-04-27 13:27:49

标签: jquery

我正在尝试获取item1的ID,但它不会在下面的代码中返回ID。有没有办法获得更高级别的功能?

我假设代码试图获取popup的ID,但这不是必需的,也不存在。我可以获得更高级别的功能ID吗?或者我可以将其作为参数传递给较低级别​​的功能吗?

$(".item1").live ("click" ,function(){
    $('.popup_pre_loading').css('display','none');
        $('.popup').fadeIn( 800, function(){
        alert((this).attr('id'));//need this for URL param
      });
      return false;
});

请注意,当警告框直接位于item的功能范围内时,此代码有效。

3 个答案:

答案 0 :(得分:7)

只需在外部函数中存储对this的引用,并在内部函数中引用它。

$(".item1").live ("click" ,function() {
    var self = this;
    $('.popup_pre_loading').css('display','none');
    $('.popup').fadeIn( 800, function(){
        alert(self.id);
    });
    return false;
});

请注意,您不需要$(self).attr('id') - 只需self.id即可!

答案 1 :(得分:3)

根据您的理解,当它直接位于item的函数中时它可以正常工作,我猜你在fadeIn函数中需要它。最简单的方法是将它分配给click函数中的变量,并在fadeIn函数中使用该变量。

$(".item1").live ("click" ,function(){
    var item1id = $(this).attr('id');
    $('.popup_pre_loading').css('display','none');
        $('.popup').fadeIn( 800, function(){
        alert(item1id); //need this for URL param
      });
      return false;
});

答案 2 :(得分:2)

$(".item1").live ("click" ,function(){
    var $item1 = $(this);
    $('.popup_pre_loading').css('display','none');
    $('.popup').fadeIn( 800, function(){
        alert((this).attr('id'));//need this for URL param
        alert($item1.attr('id'));
      });
      return false;
});