使用 jQuery 选择器获取 div 高度?

我有一个有很多行和 3 列的表。每列都有div内部。div我想获得第二列中的高度。我给 jQuery 如下:

$('#elementId tbody tr td.elment-class-2 div').height(); // works good, returns height of first rows div

现在,我想循环运行它,以便获得div第二列所有行中存在的高度。所以我写了计划的这段代码:

var count = $('#elementId tbody tr td.elment-class-2 div').length;
    $('#elementId tbody tr td.elment-class-2 div')[0]; //
    $('#elementId tbody tr td.elment-class-2 div')[1]; // and so on in a loop

但这会返回错误

$('#elementId tbody tr td.elment-class-2 div')[0]; // Uncaught TypeError: $(...)[0].height is not a function

PS:这里是 jQuery 的新手。原谅我愚蠢的错误。


慕森卡
浏览 105回答 2
2回答

素胚勾勒不出你

问题是从 jQuery 选择器返回的值不是数组,所以你不能像数组一样遍历它们。您需要使用each()jQuery 函数来执行此操作。您可以按如下方式执行此操作:$('#elementId tbody tr td.elment-class-2 div').each(function(i, ) {&nbsp;&nbsp; &nbsp; divHeight = $(divToCheck).height();&nbsp;});Thei是 the 的索引(另请注意,您不太可能在选择器中需要这种特殊性 - 它会使代码的可重用性降低并且更难以维护)如果没有您的原始 HTML,我只能在下面向您展示此工作的一般示例:$('tr div').each(function(i, divToCheck) {&nbsp; divHeight = $(divToCheck).height();&nbsp; console.log("Div "+ i + " height = "+ divHeight);});td { border:1px solid grey;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table>&nbsp; <tr>&nbsp; &nbsp; <td><div>hello</div></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td><div style="height:30px;">hello </div></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; <div style="font-size:20px">hello</div>&nbsp; &nbsp; </td>&nbsp; </tr></table>

拉莫斯之舞

我检查了你的 CodePen,似乎变量ht有错字,类需要在 TD 旁边td.elmCls,即第二部分是代码:$(document).ready(function () {&nbsp; var ht = $('table tbody tr td.elmCls').height();&nbsp; console.log(ht)&nbsp; var divs = $('tbody tr td:nth-of-type(2) div');&nbsp; divs.each(function(index, elem) {&nbsp; &nbsp;console.log(elem.innerText);&nbsp; &nbsp;var height = $(elem).height();&nbsp; &nbsp;console.log(height);&nbsp; });});您看到该错误的原因是因为当您尝试通过方法获取对象时,$()它最初会返回一个 jQuery 对象。当您然后[0]像您一样在对象上使用时$('td.elmCls')[0],您会取回本机 Javascript 节点/元素。height()该节点上没有方法,这就是您收到该错误的原因。您可以使用.each(function(index, element){ [code-here]})方法解决此问题,然后简单地打印element.innerText到控制台。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript