2011-09-19 111 views
2

這些有什麼區別,我怎麼知道什麼時候用哪個?這些POST命令有什麼區別?

$.post($(this).attr('action'), $(this).serialize(), function(response) { 
    // do something here on success 
}, 'json'); 

$.post($(this).prop('action'), $(this).serialize(), function(response) { 
    // do something here on success 
}, 'json'); 

$.post($(this).closest("form").prop('action'), $(this).serialize(), function(response) { 
    // do something here on success 
}, 'json'); 

回答

2

在這種情況下,第一個和第二個是相同的。這些函數必須從表單事件處理程序中調用。也可以使用$(this).prop/attr()$(this)[0].actionthis.action

第三種方法查找最近的表單元素,並檢索表單的action屬性。這種方法從非形式的上下文中是有用的,例如,來自button元素。

1

第一個和第二個適用於與<form>元素關聯的「提交」事件處理程序。第二種可能更好,但在實際使用中它們幾乎是一樣的。

第三個作爲<form>內的<button>或其他類似情況的「點擊」處理程序很有用。