[英]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.