繁体   English   中英

获取动态表TD的宽度

[英]Get width of the dynamic table TD

如果将动态表 TD 创建为字符串,我正在寻找有关获取动态表 TD 宽度的帮助。

例如,此方法创建一个表格来显示天气预报数据。 为了使表格的外观和感觉保持一致,我需要知道 TD 的大小,这样我就可以计算可以输入多少文本,保持每个城市、预报和温度的大小相同。

function populateForecast() {
   var output = "";
   output += "<table width=\"100%\" height=\"100%\" border=\"0\" id=\"tblResults\">";
   // loop over the weather data here.
   output += "<tr><td class=\"city-size\"><p class=\"city-font\">";
   output += "New York, NY";  // This would be a variable from the weather API
   output += "</p></td>";
   output += "<td class=\"forecast-size\"><p class=\"forecast-font\">";
   output += "Partly Cloudy"  // This would be a variable from the weather API
   output += "</p></td>";
   output += "<td class=\"temp-size\"><p class=\"temp-font\">";
   output += "71/62";  // This would be a variable from the weather API
   output += "</p></td>";
   output += "</tr>";
   output += "</table>";

   document.getElementById('weatherDiv').innerHTML = output;
  }

由于这是一个字符串,因此在尝试获取表元素的元素时返回 null。 之后我尝试使用 jquery 获取表 td 的大小,但也返回了 null。

    $(document).ready(function () {
      $('table td').each(function(){         
        console.log("Have a TD");
      });
    });

我还尝试使用 javascript 创建表,因此它不是使用字符串创建的。 这里的问题是将表格添加到 div 中。 我可以添加它的唯一方法是使用 appendChild,但是每次更新,它都会生成一个新表,我仍然无法获得宽度。

 var table = document.createElement('table'); table.setAttribute("id", "weatherTable") //for (var i = 1; i < x; i++){ for each forecast. var tr = document.createElement('tr'); var td1 = document.createElement('td'); var td2 = document.createElement('td'); td2.setAttribute("id", "forecastTable") var td3 = document.createElement('td'); var cityText = document.createTextNode('New York, NY'); var forecastText = document.createTextNode('Partly Cloudy'); var tempText = document.createTextNode('71/62'); td1.appendChild(cityText); td2.appendChild(forecastText); td3.appendChild(tempText); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); table.appendChild(tr); //} document.getElementById('weatherDiv').appendChild(table); var width = document.getElementById('forecastTable').offsetWidth; console.log(width);
 <div id="weatherDiv"></div>

// 不能 append,它添加不更新表。

使用 javascript 表,将其添加到 div 时,addendChild 可以工作,但是每 60 秒更新一次附加一个新表,而不是更新。 此外,尝试获取 object 的宽度也会返回 null。 未捕获的类型错误:无法读取 null 的属性“offsetWidth”。 我很抱歉,但每次尝试获取 TD 都会返回 null,我正在努力寻找方法。

即使在调整大小后,如何从任一方法获取表格的当前 TD 像素宽度?

append 孩子应该是这样的

 document.getElementById('weatherDiv').appendChild(table);

一个小演示

 var table = document.createElement("table") for(var i = 1; i<= 5; i ++){ var tr = document.createElement("tr"); var td = document.createElement("td") td.innerText = "<span>Text = " + i + "</span>" tr.appendChild(td) table.appendChild(tr) } document.getElementById("container").appendChild(table)
 <div id="container"> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM