2013-02-26 25 views
2

我有一個功能,一旦用戶單擊鏈接,發出ajax請求,並且如果發出請求,則鏈接不應再可點擊。使用span或div替換定位標記或p

這裏是我用來實現這一目標是什麼:

$('a[id^="rsvp_"]').click (function (e) { 
    e.preventDefault(); 
    $.post(
     $(this).data('url'), 
     function(data) { 
      $(this).replaceWith(function(){ 
       alert (data); 
       return $("<span>" + data + "</span>"); 
      }); 
     } 
    ); 
}) ; 

此代碼將適用於開始rsvp_任何標識。一切似乎都起作用,包括alert(data),但錨標記仍然存在。我只是想將錨標籤替換爲其他內容。

HTML片段看起來像這樣

<a id="rsvp_${event.id}" href="#" data-url="${createLink(action: 'myaction', params: ["eventid": event, "userid": user])}">Click to RSVP</a> 

更新

請注意,我對頁面即rsvp_1, rsvp_2, rsvp_3 ..etc

多個鏈接這樣我只是想刪除錨點標記在用戶點擊的鏈接上。不是所有的頁面

+0

你想要用返回的數據替換鏈接,或者只是確保鏈接沒有被點擊兩次? – Thomas 2013-02-26 13:51:04

+0

我想用返回的數據替換鏈接(字符串),然後確保它不可點擊。 – birdy 2013-02-26 13:51:49

回答

0
$("a").removeAttr("href"); 

更好的鏈接刪除錨點的HREF ..或

$(this).replaceWith(function(){ 
     return $("<span>" + $(this).html() + "</span>"); 
    }); 
+0

他想用返回的數據替換它,而不僅僅是刪除href。 – Archer 2013-02-26 13:47:43

1

試試這個

$(e.target).replaceWith(function(){ 
     return $("<span>" + $(this).html() + "</span>"); 
    }); 
+0

這將取代所有的鏈接。我只想替換點擊鏈接 – birdy 2013-02-26 13:53:17

+0

使用此代替「a [id^=」rsvp_「]」 – 2013-02-26 13:54:01

+0

使用$(this)而不是$(「a [id ...」) – 2013-02-26 13:54:37

2

試試這個:

$('a[id^="rsvp_"]').click(function (e) { 
    e.preventDefault(); 
    $.ajax($(this).data('url'), { 
     method: 'POST', 
     context: this 
    }).done(function(data) { 
     $(this).replaceWith("<span>" + data + "</span>"); 
    }); 
}); 
1

你可以通過使用jquery .one方法實現相同,它確保每個se lected元素只能點擊一次。

在這樣的情況下,如果可能的話,我會親自改變所有的錨標籤p或跨度默認,然後應用在諸如選定元素單擊一次:

$('p[id^="rsvp_"]').one ("click", function (e) { 
    e.preventDefault(); 
    $.post(
     $(this).data('url'), 
     function(data) { 
      $(this).replaceWith(function(){ 
       alert (data); 
       return $("<span>" + data + "</span>"); 
      }); 
     } 
    ); 
}); 

more here