function change() {
var tds = document.getElementsByTagName("td");
var tds2 = tds.className;
console.log(tds);
for (var i = 0; i < tds.length; i++) {
if (tds[i].className === "marked") {
tds[i].className = "UNmarked";
} else {
tds[i].className = "marked";
}
}
}
function generTab(rows, cols) {
var html = "<table id='tb01'>";
for (var i = 1; i <= rows; i++) {
html += "<tr>"
for (var j = 1; j <= cols; j++) {
html += "<td class='marked' onclick='change()'>" + "</td>";
}
html += "</tr>"
}
return html + "</table>";
}
td.marked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: white;
}
td.UNmarked {
height: 50px;
width: 50px;
border: solid thin black;
cursor: pointer;
background-color: purple;
}
<div class="line">
Number of rows:
<input type="text" id="rows" />
</div>
<div class="line">
Number of cols:
<input type="text" id="cols" />
<span class="error"></span>
</div>
<input type="button" value="Generuj" id="gener" />
</div>
<div id="scene"></div>
我正在自己生成表格,我想通过点击它来更改指定<td>
的类。问题是当我点击任何<td>
时,它会更改所有类的类,但我想更改我点击的<td>
类。
答案 0 :(得分:1)
可能你可以用一个类做以下事情:
library(stringr)
string <- "abcd efgh"
pattern <- "([a-zA-Z]{1})(\\S+)"
replacement <- "\\U\\1\\L\\2"
exp_outcome <- "Abcd Efgh"
# not what is expected..
str_replace_all(string,
pattern,
replacement)
# RESULT: [1] "1Lbcd 1Lfgh"
# check pattern matches
str_replace_all(string,
pattern,
"\\1 \\2")
# works!
gsub(pattern, replacement, x = string, perl = TRUE)
&#13;
var tds = document.querySelectorAll("td");
tds.forEach(function(td){
td.addEventListener('click', function(){
this.classList.toggle('marked')
});
});
&#13;
td {
border: 1px solid lightgray;
padding: 10px;
font-size: 20px;
}
.marked{
background-color: #4CAF50;
color: white;
}
&#13;
答案 1 :(得分:0)
向所有click
元素添加td
个事件侦听器,并实现一个简单的onClick
函数,用于添加/删除所需的css类。
const tds = Array.from(document.querySelectorAll('td'));
const onClick = ({ target }) => {
tds.forEach(td => td === target ? td.classList.add('active') : td.classList.remove('active'))
}
tds.forEach(td => td.addEventListener('click', onClick));
.active {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
</body>
</html>
答案 2 :(得分:0)
您编写的代码应该是切换文档中所有td
的类。我相信你正试图改变被点击的td的类。要做到这一点,尝试类似的事情(事先道歉,因为我在手机上):
function change(e) {
let td = e.target;
if (td.classList.contains('marked')) {
td.className = 'UNmarked';
} else {
td.className = 'marked';
}
}
并确保该更改绑定为每个td的click事件。
答案 3 :(得分:-1)
如果你可以使用jQuery ......
$("td").click(function(){
$(this).toggleClass("marked")
.toggleClass("UNmarked");
});