2014-08-29 64 views
0

我已經在局部視圖下面的代碼:困惑與ActionLink的做內部的Ajax調用for循環

foreach (var documentFolder in Model.DocumentFolders){ 
    <span id="Folder"> 
     @Html.ActionLink(documentFolder.DisplayNameProperty, "ControllerAction", "Controller", null, new{@name = documentFolder.IDProperty, @id = "lbGetFile", @class = "textLink", @style = "text-decoration: underline; color: blue; cursor: pointer;"}) 
    </span> 
} 

我有這樣的jQuery代碼:

$("#lbGetFile").click(function(){ 
     debugger; 
     $.ajax({ 
      url: this.href, 
      type: "POST", 
      data: { selectedFolderID: $("#lbGetFile").attr('name') }, 
      error: function (jqXHR, textStatus, errorThrown) { 
       debugger; 
      }, 
      success: function (data) { 
       debugger; 
      } 
     }); 
     return false; 
    }); 

什麼我注意到是隻有我的for循環的第一個項目才能正確地返回成功函數。它可能是因爲for循環中的每個項目都有相同的id,但我無法弄清楚該怎麼辦?

此外,我會認爲,而不是一個for循環編輯器模板應該在這裏更好地工作,但可以成功的Ajax調用正確地重寫編輯器模板區域?

+2

這是因爲相同的ID確實。但是,你可以很容易地完全擺脫它。只要選擇一個不同的選擇器,比如類和元素,然後在處理器內部使用'this' – Andrei 2014-08-29 15:43:56

+0

@andrei,那麼......如何在動態時編寫JQuery選擇器?我可以理解使用$(「#hello .world」)選擇基於say「id ='hello'class ='world'」的標籤。 – Jason 2014-08-29 15:51:39

+0

擴大答案。希望它能澄清這個 – Andrei 2014-08-29 16:10:21

回答

0

你的問題確實是由於相同的ID。不僅如此,您所有的span標籤也具有相同的標識Folder。完全重新訪問它並從代碼中刪除ID可能是一個好主意。所以標記可能是這樣的:

foreach (var documentFolder in Model.DocumentFolders){ 
    <span class="folder"> 
     @Html.ActionLink(documentFolder.DisplayNameProperty, "ControllerAction", "Controller", null, new{@name = documentFolder.IDProperty, @class = "textLink", @style = "text-decoration: underline; color: blue; cursor: pointer;"}) 
    </span> 
} 

請注意,不再有任何標識,類代替。類允許輕鬆重複並且不引起衝突。

至於JavaScript的 - 這裏是你如何查詢:

$("span.folder .textLink").click(function(){ 

這將選擇您需要的所有鏈接。而且您已經知道您可以在處理程序中使用this來引用當前單擊的元素。

+0

Thx @Andrei,這很好。對於像我這樣混淆的人來說,選擇這種結構''在jQuery中去''(「#Folder .textLink .textLink 「)。單擊(函數(){' – Jason 2014-08-29 18:10:57