gpt4 book ai didi

javascript - 表格单元格(td)子项?

转载 作者:行者123 更新时间:2023-12-01 02:30:48 29 4
gpt4 key购买 nike

我正在尝试搜索其中包含子项(文本区域)的表格单元格。我努力了td.children.value,td.childNodes.value,td.firstChild.value,td.lastChild.value,td.textarea.value...这些都不起作用。这是我的片段:

addCell = function() {
var table = document.getElementById('myTable');

var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createElement('textarea');

table.appendChild(tr);
tr.appendChild(td);
td.appendChild(txt);
}

searchT = function() {
var table = document.getElementById('myTable');
var search = document.getElementById('search');
var tr = document.getElementsByTagName('tr');
var td = document.getElementsByTagName('td');

if (search.value === td.textarea.value) {
alert('hello');
}

/* I have tried:

td.childNodes.value
td.children.value
td.firstChild.value
td.lastChild.value
td.textarea.value
*/

}
td {
background-color: #ccc;
width: 100px;
height: 20px;
}

textarea {
resize: none;
}

.search {
width: 100px;
}
<button onclick="addCell()">
add
</button>

<input id="search" placeholder="search">
<button onclick="searchT()">
search
</button>

<table id="myTable">
<tr>
<td>
<textarea></textarea>
</td>
</tr>
</table>

最佳答案

当你这样做时document.getElementsByTagName() ,这将返回 document 上所有项目的列表。其中包含该标签名称。为了查明它是否存在于该列表中(我假设这就是您想要的),那么您必须循环查找 getElementsByTagName() 返回的列表。

我还假设您想要添加一个表格,其中包含您在 <input> 中输入的内容所以我在addCell()中添加了这一点.

addCell = function() {
var table = document.getElementById('myTable');

var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createElement('textarea');
var search = document.getElementById('search'); // Get value in input field

table.appendChild(tr);
tr.appendChild(td);
txt.innerHTML = search.value; // Set value to table
td.appendChild(txt);

}

searchT = function() {
var search = document.getElementById('search');
var textareas = document.getElementsByTagName('textarea'); // Get the textareas instead

for(var i = 0; i < textareas.length; i++) {
if(search.value === textareas[i].innerHTML) { // If the text matches the search field
console.log("Found: " + search.value + " at index: " + i);
}
}
}
td {
background-color: #ccc;
width: 100px;
height: 20px;
}

textarea {
resize: none;
}

.search {
width: 100px;
}
<button onclick="addCell()">
add
</button>

<input id="search" placeholder="search">
<button onclick="searchT()">
search
</button>

<table id="myTable">
<tr>
<td>
<textarea readonly="readonly">Template</textarea> <!-- This doesn't have to be readonly but I made it Note: readonly="readonly" is only for valid XHTML. It could be left as readonly without the assignment for valid HTML -->
</td>
</tr>
</table>

如果您好奇,可以阅读有关 getElementsByTagName() 的更多信息。 here.

关于javascript - 表格单元格(td)子项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48324141/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com