2 回答

TA貢獻1827條經驗 獲得超9個贊
問題是從 jQuery 選擇器返回的值不是數組,所以你不能像數組一樣遍歷它們。您需要使用each()jQuery 函數來執行此操作。
您可以按如下方式執行此操作:
$('#elementId tbody tr td.elment-class-2 div').each(function(i, ) {
divHeight = $(divToCheck).height();
});
Thei是 the 的索引(另請注意,您不太可能在選擇器中需要這種特殊性 - 它會使代碼的可重用性降低并且更難以維護)
如果沒有您的原始 HTML,我只能在下面向您展示此工作的一般示例:
$('tr div').each(function(i, divToCheck) {
divHeight = $(divToCheck).height();
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>
<tr>
<td><div>hello</div></td>
</tr>
<tr>
<td><div style="height:30px;">hello </div></td>
</tr>
<tr>
<td>
<div style="font-size:20px">hello</div>
</td>
</tr>
</table>

TA貢獻1820條經驗 獲得超10個贊
我檢查了你的 CodePen,似乎變量ht有錯字,類需要在 TD 旁邊td.elmCls,即第二部分是代碼:
$(document).ready(function () {
var ht = $('table tbody tr td.elmCls').height();
console.log(ht)
var divs = $('tbody tr td:nth-of-type(2) div');
divs.each(function(index, elem) {
console.log(elem.innerText);
var height = $(elem).height();
console.log(height);
});
});
您看到該錯誤的原因是因為當您嘗試通過方法獲取對象時,$()它最初會返回一個 jQuery 對象。當您然后[0]像您一樣在對象上使用時$('td.elmCls')[0],您會取回本機 Javascript 節點/元素。height()該節點上沒有方法,這就是您收到該錯誤的原因。
您可以使用.each(function(index, element){ [code-here]})方法解決此問題,然后簡單地打印element.innerText到控制臺。
添加回答
舉報