亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用append()插入的HTML表格列沒有給出預期的行為

使用append()插入的HTML表格列沒有給出預期的行為

偶然的你 2024-01-18 20:38:38
我正在嘗試制作一個交互式表格網格,當您調整邊緣大小時,其他表格也會調整大小。到目前為止,一切似乎都很順利,直到為了添加新列,您必須單擊按鈕。預期行為:如果您嘗試拖動最初兩列的邊緣,它們會完美地工作。但是,如果通過單擊按鈕添加新列,該列將添加到表中,但與其他兩列的行為不匹配。如何使用按鈕添加所有列以遵循相同的行為?
查看完整描述

1 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

您的代碼不起作用,因為在調用回調時,事件偵聽器僅附加到最初的兩列$(document).ready。一個簡單的解決方案是 AddListeners()每次插入新列時調用,如下所示:


function AddListeners() {

    var thElm;

    var startOffsetX;

    var startOffsetY;


    Array.prototype.forEach.call(

      document.querySelectorAll("table th"),

      function(th) {

        th.style.position = 'relative';


        var grip = document.createElement('div');

        grip.innerHTML = " ";

        grip.style.top = 0;

        grip.style.right = 0;

        grip.style.bottom = 0;

        grip.style.width = '5px';

        grip.style.position = 'absolute';

        grip.style.cursor = 'col-resize';

        grip.addEventListener('mousedown', function(e) {

          thElm = th;

          startOffsetX = th.offsetWidth - e.pageX;

          startOffsetY = th.offsetHeight - e.pageY;

        });


        th.appendChild(grip);

      });


    document.addEventListener('mousemove', function(e) {

      if (thElm) {

        thElm.style.width = startOffsetX + e.pageX + 'px';

        thElm.style.height = startOffsetY + e.pageY + 'px';

      }

    });


    document.addEventListener('mouseup', function() {

      thElm = undefined;

    });

  };


$(document).ready(function() {

  AddListeners();


  

})


var iter = 2;


function AddColumn() {

  var myform = $('#myTable');

  myform.find('tr').each(function() {

    var trow = $(this);

    iter += 1;

    if (trow.index() === 0) {

      trow.append('<th><div style="top: 0px; right: 0px; bottom: 0px; width: 5px; position: absolute; cursor: col-resize;">&nbsp;</div>th ' + iter + '</th>');

    } else {

      trow.append('<td>th ' + iter + '</td>');

    }

  });

  AddListeners();

}

table {

  border-width: 1px;

  border-style: solid;

  border-color: black;

  border-collapse: collapse;

}


table td {

  border-width: 1px;

  border-style: solid;

  border-color: black;

}


table th {

  border-width: 1px;

  border-style: solid;

  border-color: black;

  background-color: green;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<a onclick="AddColumn()">Add column</a>


<table id="myTable">

  <thead>

    <tr>

      <th>th 1</th>

      <th>th 2</th>

    </tr>

  </thead>

</table>

但這個解決方案很丑陋,因為它會重做為早期存在的列添加的偵聽器。更好的解決方案需要您將每列的事件附加過程與回調中解耦AddListeners(),并分別在Array.prototype.forEach.call和 中 調用它AddColumn()。但這是另一個問題了。



查看完整回答
反對 回復 2024-01-18
  • 1 回答
  • 0 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號