2010-05-16 70 views
1

我試圖將對象傳遞到函數,但認爲有以$(這)個問題實際上不是處於傳遞中的點有效。

$('textarea[name*=quote]').live('bind',function(){ 

}).limit('10',$(this).parents('form').children().find('span[name*=qc]')); 

第二個參數是一個字符串或像$('span#qc')這樣的對象,但我也希望能夠傳入一個引用當前對象的對象。

爲什麼?因爲我在同一頁面上有多個表單,每個表單都包含textarea#quote,所以根據選擇的表單,我希望能夠引用同一表單中的特定元素。

任何??

+2

您不應該有重複的ID;改用類名。 – SLaks 2010-05-16 02:22:12

+0

這是什麼?我的意思是,你在jQuery.each中嗎?提供更多的代碼,沒有辦法知道該範圍內的「this」是什麼。 – BrunoLM 2010-05-16 02:34:20

回答

1

您需要進行單獨的調用使用.each每個單獨的實例,就像這樣:

$('textarea#quote').each(function() { 
    $(this).live('bind',function(){ 

    }).limit('10',$(this).parents('form').children().find('span#qc')); 
}); 
+0

謝謝SLaks,即使它在.each中,那麼它是否會通過ajax等更新任何新的textarea#quote字段? – regan 2010-05-16 03:32:09

+0

@regan - 它不會,['.live()'](http://api.jquery.com/live/)是一個事件處理程序,它不能在新元素上運行插件......除非它通過一個'.live()'事件可以監聽,這通常不是你想要的。 – 2010-05-16 11:36:54

1

擁有訪問權限的$(this)綁定所有的人,使用.each(),像這樣:

$('textarea[name*=quote]').each(function() { 
    $(this).limit('10',$(this).closest('form').find('span[name*=qc]')); 
}); 

如果您需要.live()類似功能的第二部分,您需要使用.livequery(),如下所示:

$('textarea[name*=quote]').livequery(function() { 
    $(this).limit('10',$(this).closest('form').find('span[name*=qc]')); 
}); 

或者,可以像第一個示例那樣綁定它們,並且在加載新元素時也會綁定,例如,如果你使用$.ajax(),它應該是這樣的:在這裏

$.ajax({ 
    url: blah.html 
    success: function(data) { 
    //do something with data 
    $('textarea[name*=quote]', data).each(function() { 
    $(this).limit('10',$(this).closest('form').find('span[name*=qc]')); 
    }); 
    } 
}); 

的關鍵是, datait provides a context to search in,所以這只是在傳回的數據中發現的元素執行。您也可以在功能包裝是爲了防止重複的代碼,像這樣:

function bindStuff(context) { 
    $('textarea[name*=quote]', context || document).each(function() { 
    $(this).limit('10',$(this).closest('form').find('span[name*=qc]')); 
    }); 
} 

document.ready,叫bindStuff(document),在$.ajax,你會打電話bindStuff(data)

相關問題