2012-02-28 20 views
0

爲什麼第一個警報會說未定義?請注意,警報存在,並且文本框僅在我關閉警報時出現。jQuery的選擇器.attrib('id')的第一部分視圖未定義

enter image description here

隨後的 「新」 點擊警報 「RowId的」。在我解僱警報後,我看到兩個框。 enter image description here

這是我的視圖與Ajax.Action鏈接是InserterAfter。

@Ajax.ActionLink("New", "_New", new { Controller = "Test" } 
    , new AjaxOptions() 
     { InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "divNew" }) 

<div id="divNew" /> 

這是我的偏愛。

RowId: @Html.TextBox("RowId")<br /> 
<script language="javascript"> 
    $(document).ready(function() 
    { 
     alert($('input[name="RowId"]').attr('Id')); 
    }); 
</script> 

回答

2

嘗試在你的主要觀點如下:

<!-- TODO: This script should be moved to a separate javascript file 
    because you should never mix markup and javascript. But for the 
    purpose of this demonstration I have left it in the view 
--> 
<script type="text/javascript"> 
    var onSuccess = function (result) { 
     $('#divNew').append(result); 
    }; 
</script> 

@Ajax.ActionLink(
    "New", 
    "_New", 
    new { controller = "Test" }, 
    new AjaxOptions() { OnSuccess = "onSuccess" } 
) 
<div id="divNew" /> 

或扔掉Ajax.*助手,並使用普通的舊的jQuery:

<!-- TODO: This script should be moved to a separate javascript file 
    because you should never mix markup and javascript. But for the 
    purpose of this demonstration I have left it in the view 
--> 
<script type="text/javascript"> 
    $(function() { 
     $('#mylink').click(function (result) { 
      $.ajax(this.href, { 
       success: function (result) { 
        $('#divNew').append(result);   
       } 
      }); 
      return false; 
     }); 
    }); 
</script> 

@Html.ActionLink(
    "New", 
    "_New", 
    new { 
     controller = "Test" 
    }, 
    new { 
     id = "mylink" 
    } 
) 
<div id="divNew" /> 

這是說,如果我沒有錯,如果我的記憶力好,我想我已經評論過類似的以前的問題,但我會在這裏重複讓其他人可以看到它,以及:

把任何JavaScript部分或任何意見任何責任。 Javascript屬於單獨的文件,不應該與標記混合使用。

我看到人們一遍又一遍地犯這個錯誤,我認爲它的重要性在於指出它。

P.S:你可能想用.attr('id')而不是.attr('Id')

+1

+1您的意見:) – 2012-02-28 21:49:15

+0

謝謝。我會把所有的js分開! – 2012-02-28 22:00:57

+0

我會按照你的建議去使用jquery ajax。我打算讓.js文件像後面的代碼一樣用於視圖。 – 2012-02-28 22:02:45