运行 javascript 有条件地运行 - Razor,HTML

Running javascript function conditionally - Razor, HTML

现在我有一个 table 是使用用户选择 + 数据动态创建的。有时,数据有错误,我想在 table 中让用户知道。

Razor(link 带你去~/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 添加标题(以便工具提示可以使用它)并更改 link 的颜色,但仅当 errorConditions 为真时。

现在当我 运行 时,什么也没有发生。 addErrorMessage 从不调用,但所有信息都在我期望的地方(如 link 具有正确的 ID 等)。

有人知道吗?

onload 仅在 <body> 上受支持,但高度 建议您不要使用内联事件处理程序!

使用内联脚本,像这样(使用 jQuery 因为你似乎在使用它):

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