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

Running javascript function conditionally - Razor, HTML

本文关键字:-Razor HTML 函数 javascript 运行 有条件      更新时间:2023-09-26

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

Razor(链接将带您访问~/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等)。

有人有主意吗?

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

使用内联脚本,如下所示(使用jQuery,因为您似乎在使用它):

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