簡體   English   中英

HTML表格更改單元格顏色

[英]HTML table change cell color

我有一個HTML表,單擊按鈕后會向其中添加行。 那部分工作正常:

function ic_add_supplier_line(){
   var table = document.getElementById("ic_current_pricing");
   var count = $('#ic_current_pricing tr').length;
   var row = table.insertRow(count); 
  for (i = 0; i < 8; i++) {
     var cell = row.insertCell(i); 
     var cell_id = "ic_q_" + String(i) +"_" + String(count)
     cell.innerHTML = "<input id=" + cell_id + " style='width:100%;' type='text' ondblclick='select_supplier(this.id)' >" 
  } 
}

雙擊單元格時,我希望更改單元格背景色。

  function select_supplier(elm_id) {
     var cur_row = elm_id.slice(-1)
     var table = document.getElementById("ic_current_pricing");
     var rows = table.getElementsByTagName("tr") ;
     for (var i=0; i<rows.length; i++) {
        if (i== cur_row){
           for (j =0; j<8; j++){
               rows[i].cells[j].className="on"
           }    
        }else{
           for (j =0; j<8; j++){
           rows[i].cells[j].className=""        
        }
     }
   }
}

和CSS

.on{
   background-color:green ;
 }

只有邊框/輪廓線正在改變顏色。 細胞保持白色。 感謝任何幫助。 提前致謝。

問題在於生成的輸入字段與實際單元格重疊,因此,當發生顏色更改時,由於輸入字段占用了99%的顏色,因此它不會顯示整個單元格。 通過更改和分配“ on”類以影響輸入字段,我們得到了OP期望的最終結果。

一個解決方案,期望相應嗎?
(更改整個行的顏色_和ES6語法更簡單...)

 const ic_Table = document.querySelector("#ic_current_pricing tbody") function ic_add_supplier_line() { let count = ic_Table.rows.length , newRow = ic_Table.insertRow( count ) for (let i=0; i < 4; i++) // changed 8 to 4 { newRow .insertCell(i) .innerHTML = `<input id="ic_${i}_${count}" type="text" >` } } ic_Table.ondblclick=e=> // event delegation for double click for every <input { if(!e.target.tagName.toLowerCase=='input') return let TR_parent = e.target.parentNode.parentNode ic_Table.querySelectorAll('tr').forEach(xTR=> xTR.className = (xTR===TR_parent) ? 'on' : '' ) } R_plus.onclick = ic_add_supplier_line 
 table { border-collapse: collapse; margin: 1em } td { border: 1px solid grey; padding: .5em 0; height: 1em; width:110px; text-align:center; } td input[type=text] { width:80px !important } .on { background-color:green ; } 
 <button id="R_plus">Add Row</button> <table id="ic_current_pricing"> <tbody> </tbody> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM