[英]Javascript check boxes based on text in rows
我正在嘗試將其轉換為: 使用JQuery選擇表行並選中復選框
進入普通的javascript,因為我處於無法使用jquery的情況。
這是原始的
$("table tr").each(function () {
if ($(this).find("td:eq(1)").text().trim() == '2013-03-21') {
$(this).find("input[type=checkbox]").attr("checked", true);
}
});
這是我到目前為止所擁有的,並且我確信它已經走了:
var elements = [].slice.call(document.querySelectorAll("table tr"));
Array.prototype.forEach(elements, function(){
var tdText = this.querySelectorAll("td").textContent
if (tdText == '2013-03-21') {
this.querySelectorAll("input[type=checkbox]").setAttribute("checked", true);
}
});
這是原始表:
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
代碼var tdText = this.querySelectorAll("td").textContent
將返回未定義的textContent,因為您引用的是tr
的NodeList
。 您可以遍歷它,然后可以獲得td
的內容:
let rows = Array.prototype.slice.call(document.querySelectorAll('table tr'));
let textDate = '2013-03-21';
rows.map((row) => {
let cells = Array.prototype.slice.call(row.querySelectorAll('td'));
for (let i = 0, length = cells.length; i < length; i++) {
if (cells[i].textContent === textDate) {
let cb = row.querySelectorAll('input[type=checkbox]');
cb[0].checked = true;
return;
}
}
});
ElemCollection.forEach.call
而不是Array#slice.call
因為HTMLCollection
沒有forEach
方法 td
元素中選擇文本時使用[1]
索引 this
在Array#forEach
不是指element
,使用first
的參數Array#forEach
回調函數,它是item
的array
Array.prototype.forEach.call(document.querySelectorAll("table tr"), function(elem) { var tdText = elem.querySelectorAll("td")[1].textContent; if (tdText === '2013-03-21') { elem.querySelector("input[type=checkbox]").setAttribute("checked", true); } });
<table> <tr> <td>Record1</td> <td>2013-03-21</td> <td> <input type="checkbox" /> </td> </tr> <tr> <td>Record2</td> <td>2013-03-22</td> <td> <input type="checkbox" /> </td> </tr> <tr> <td>Record3</td> <td>2013-03-21</td> <td> <input type="checkbox" /> </td> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.