加载文本字段时自动调用JS函数

时间:2017-11-28 10:30:09

标签: javascript jquery razor

我有Razor页面,我想在工作日显示索引表中的翻译。我希望通过简单的JS函数在客户端完成并显示这个计算。

页:

@foreach (var item in Model.Trainings) {
    <tr>
        <td>
            <p call_function?='getWeekday(@item.Since)'></p> <!-- I want weekday to be displayed here -->
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Since)
        </td>
    </tr>
}

JS功能:

<script>
        function getWeekday(date) {
            var weekdays = ({
                et: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"],
                en: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
            });

            var d = new Date(date);
            var n = weekdays['et'][d.getDay()]; // currentCultureCode
            return n;
        }
</script>

是否有名称或表达方式如何命名这种方法?

1 个答案:

答案 0 :(得分:1)

在DOM中创建元素时,没有引发元素级事件。

相反,您可以创建HTML,然后在加载DOM时运行一个函数。您还可以将来自item.Since属性的日期存储在元素的data属性中,以使代码更具可扩展性,如下所示:

&#13;
&#13;
function getWeekday(date) {
  var weekdays = ({
    et: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"],
    en: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  });

  var d = new Date(date);
  var n = weekdays['et'][d.getDay()]; // currentCultureCode
  return n;
}

[].forEach.call(document.querySelectorAll('table p'), function(p) {
  var date = new Date(p.dataset.since);
  p.textContent = getWeekday(date);
});
&#13;
<table>
  <tr>
    <td><p data-since="2017-11-28"></p></td>
    <td>2017-11-28</td>
  </tr>
  <tr>
    <td><p data-since="2017-11-29"></p></td>
    <td>2017-11-29</td>
  </tr>
</table>
&#13;
&#13;
&#13;

或者在jQuery中:

jQuery(function($) {
  $('table p').text(function() {
    var date = new Date($(this).data('since'));
    return getWeekday(date);
  });
});