Jquery UI 位置问题:目标在窗口中的位置很重要吗?

问题描述

使用数据表 + UI 位置。目标是在每个 DataTable 行的顶部放置一个工具栏(将单元格内容向下填充以腾出空间。)我在 'draw' 事件上创建工具栏,将其附加到行中的第一个单元格,然后将其定位在行的左上角。它适用于第一行,但不适用于后续行 - 除非我向下滚动以便在绘制工具栏时在屏幕上可以看到每一行。

澄清:工具栏是用正确的信息绘制的,并且在正确的行中,除非它们的行在视口中,否则它们不会被放置在我想要的位置。

    // create an array of reference objects for the toolbars
    var aReviews = [];
    $("tbody tr[role=row] div.place-review").each(function () {
        aReviews.push($(this));
    })
    var safetyCounter = 0; // if there's a problem,don't just run forever
    // run in an interval so I can scoll along and watch the toolbars draw
    var reviewInterval = setInterval(() => {
        if (aReviews.length == 0 || safetyCounter == 50) {
            // we've done what there is to do or there's an issue.
            // in any case,quit.
            clearInterval(reviewInterval);
            return;
        }
        // get the first reference objects in the array
        const C = $(aReviews[0]);
        // get the stuff to display in the toolbar
        const data = dashboard.getColumnData($,C);
        const idapp = data.idapp;
        const iddeal = data.iddeal;
        const e = $(`<div class='review-interview-bar'>Hello World ${idapp} ${iddeal}</div>`);
        // append the toolbar to the cell
        C.closest('td').append(e);
        // put my toolbar at the top of the cell 
        e.position({ my: 'left top',at: 'left top',of: C.closest('td') });
        // remove the reference class so we don't draw more than once.
        C.removeClass("place-review");
        // take the current item off the list
        aReviews.shift();
        safetyCounter++;
    },2000);
}

显然我不能要求我的用户向下滚动以让工具栏正确加载。我怎样才能在需要的地方找到工具栏?如果需要的话,我可以在行滚动到视图中时将工具栏移动到位,但是我如何检测滚动到视图中的行?

解决方法

考虑以下事项。

$(function() {
  // create a jQuery Object of the Table Body Rows
  var aReviews = $("tbody tr[role=row]");

  // Function to add the Toolbar to a Target (Row)
  // Data Input,and Target to append to
  function addItem(d,t) {
    var idapp = d.idapp;
    var iddeal = d.iddeal;
    var e = $("<div>",{
      class: "review-interview-bar"
    }).html("Hello World. " + idapp + "," + iddeal).appendTo(t);
    e.position({
      my: 'left top',at: 'left top',of: t
    });
    t.closests("tr").find(".place-review").removeClass("place-review");
  }

  // Iterate each row
  aReviews.each(function(i,row) {
    // Check for place-review class inside the Row
    if ($(".place-review",row).length) {
      // Wait 2 seconds. then add the toolbar
      setTimeout(function() {
        addItem(dashboard.getColumnData($,$(".place-review",row)),$("td:first",row));
      },2000);
    }
    // Move on to next row
  });
});

查看更多:

.each() 方法旨在使 DOM 循环构造简洁且不易出错。当被调用时,它遍历作为 jQuery 对象一部分的 DOM 元素。每次回调运行时,都会传递当前循环迭代,从 0 开始。更重要的是,回调是在当前 DOM 元素的上下文中触发的,因此关键字 this 指的是该元素。

当循环运行时,您将每次都使用 .position() 和一个唯一的目标。您可能需要 .offset(),这很难说。如果您需要更多帮助,则必须提供 Minimal,Reproducible Example