在页面加载时调用的淘汰 JS 鼠标悬停事件

Knockout JS mouseover event being called on pageload

本文关键字:JS 淘汰 鼠标 悬停 事件 调用 加载      更新时间:2023-09-26

我有一个鼠标悬停事件通过挖空附加到一堆输入。由于输入位于 ko foreach 块中,因此正在创建其中的许多内容,并且在页面加载时,将为页面上添加的每个输入调用 mouseover 事件。这使我的页面加载速度很慢。知道为什么在页面加载时调用该事件吗?

<!-- ko foreach: FilteredForecasts -->
     <td>
          <input class="tiny" type="number" min="0" max="80" data-bind="disable: Elapsed() || (!$parent.ResourceId() || $parent.EditingName()), value: Hours, css: { 'pending': Pending, 'saved': !Pending() && Hours() && !Elapsed(), 'highlighted': Highlighted, 'elapsed': Elapsed }, attr: { id: 'h_' + $index(), title: (!$parent.ResourceId() || $parent.EditingName() ? 'You must first save a resource to enter hours.' : TotalHoursString()) }, event: { mouseover: UpdateTotalHours($parent.ResourceId()) }" />
     </td>
<!-- /ko -->

self.UpdateTotalHours = function (resourceId) {
    if ((resourceId != null && resourceId != undefined) && self.Week() && self.Year() && (self.TotalHours() === null || self.TotalHours() === undefined)) {
        alert('here');
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf8',
            url: staffingUtilities.baseUrl + 'Forecasting/GetResourceTotalUsage/',
            data: JSON.stringify({
                id: resourceId,
                year: self.Year(),
                week: self.Week()
            }),
            success: function (data) {
                if (data == 0) {
                    self.TotalHours(null);
                    return;
                }
                self.TotalHours(data);
            }
        });
    }
};
您需要将

鼠标悬停调用包装在一个函数中,当绑定对象时,括号会导致执行 UpdateTotalHours:

mouseover: function(){ UpdateTotalHours($parent.ResourceId()); }

请参阅:http://knockoutjs.com/documentation/event-binding.html