繁体   English   中英

另一个简单的jQuery问题

[英]Another Easy jQuery Question

我有下面的代码,我想创建一个IF语句,以便只为特定的HREF调用loadScript函数。 但是,当我尝试提醒href的值时,它将返回“未定义” ...

非常感谢,J

$(document).ready(function()
        {
            $('.jNav').click(function()
            {
                $('#sandbox').load($(this).attr('href'),function() 
                {
                    alert("From here " + $(this).attr('href') + " to here.");
                    loadScript();
                });
                return false;
            });
        });

您的问题只是范围界定。 在您的load()回调中,这是指您要调用load()的元素,恰好是$('#sandbox') ,因此:no href。 通常我要做的是这样的:

$('.jNav').click(function()
{
  var self = this;
  $('#sandbox').load($(this).attr('href'),function() 
  {
    // Notice the use of self here, as we declared above
    alert("From here " + $(self).attr('href') + " to here.");
    loadScript();
  });
  return false;
});

这样做可以确保您仍然可以从load()回调内部找到所单击的内容。

问题是上下文之一:警报中对$(this)的调用是指$('#sandbox')而不是$('.jNav') 只需定义一个变量供您首次参考。

当您在$('#sandbox').load回调中时, this引用是$('#sandbox') ,而不是$('.jNav') 如果要警告href,请将其(或this的引用)保存在变量中。

$('.jNav').click(function(){
  var that = this;
  $('#sandbox').load($(this).attr('href'),function(){
    alert($(that).attr('href'));
    //...
  });
}

要么

$('.jNav').click(function(){
  var href = $(this).attr('href');
  $('#sandbox').load($(this).attr('href'),function(){
    alert(href);
    //...
  });
}

$(this).jNav ,但是在您的回调中它现在是#sandbox 在将变量呈现给您的位置预缓存该变量,然后在任何需要的地方使用它。

我在Groovetrain的答案上稍有改进,我写道:

$('.jNav').click(function(event) {
  var $self = $(this);
  var href  = $self.attr('href');

  $('#sandbox').load(href, function() {
    alert("From here " + href + " to here.");
    loadScript();
  });

  event.preventDefault(); // better than `return false`
});

在您最里面的函数中,上下文( this )被设置为#sandbox元素。 您将需要事先从.jNav元素获取href属性并将其存储在变量中。

范例程式码

请注意功能的哪个部分中的“ this”。 在最里面的函数中,您从$('#sandbox')调用它,我怀疑它没有href属性。 最好的解决方案可能是将href的值传递给函数或将其存储在变量中。

$(document).ready(function()
        {
            $('.jNav').click(function()
            {
                $('#sandbox').load($(this).attr('href'),function() 
                {
                    alert("From here " + $(this).parent().attr('href') + " to here.");
                    loadScript();
                });
                return false;
            });
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM