2015-03-31 15 views
0

現在我有一個使用用戶選擇+數據動態創建的表。有時,數據存在錯誤,我想讓用戶知道表中的數據。有條件地運行javascript函數 - 剃刀,HTML

剃刀(該鏈接將帶您到〜/ ControllerName/givenID)

<tr id="@givenID"> 
    <td>@Html.ActionLink(name, someMethod, "ControllerName", new { id = givenID }, new { title = "", id = givenID })</td> 

    @if (errorConditions) 
    { 
    <div id="@givenID" onload="addErrorMessage(this)" data-test="ErrorMessage" style="display: none"></div> 
    } 
</tr> 

的Javascript

$(function() { 
    //adding custom tooltip to document 
    $(document).tooltip(); 

    //adding error message to standard 
    function addErrorMessage(element) { 
    var theElemOfID = document.getElementById(element.id); 
    theElemOfID.title = element.attr("data-test"); 
    theElemOfID.style.color = rgb(255, 0, 0); 
    } }); 

我想一個標題添加到ActionLink的(因此它可以通過使用工具提示),也可以改變鏈接的顏色,但只有在errorConditions爲true時。

現在,當我跑步時,沒有任何反應。 addErrorMessage永遠不會調用,但所有信息都在我期望的地方(如鏈接中有正確的ID等)。

有沒有人有想法?

+0

不要使用'onload'。除「」之外,它不受支持。 – Toothbrush 2015-03-31 20:49:01

回答

0

onload僅支持在<body>,但它是高度建議您不使用內聯事件處理程序!

(因爲你似乎可以用它使用jQuery)使用內聯腳本,像這樣:

@if (errorConditions) 
{ 
    <div id="@givenID" data-test="ErrorMessage" style="display: none"></div> 
    <script> 
     $(function() { 
      addErrorMessage($('#@givenID')); 
     }); 
    </script> 
} 
+0

我甚至沒有想過這樣做,謝謝。 – lisolm 2015-04-01 14:24:02