1、bind 函数为每个td节点绑定click事件,当某个td节点被点击时class变为current,同时以该td为中心的同一行和同一列td节点class变为wrap,具体效果参考以下图片
2、每次click后,请清空所有不需要变动的td节点的class
3、请不要手动调用bind函数
4、当前界面为系统生成 9 * 9 表格,执行 bind 函数,并点击其中td后的效果
5、请不要手动修改html和css
6、不要使用第三方插件
function bind() {
var tr = document.querySelectorAll('tr')
var td =document.querySelectorAll('td')
for(var i=0;i<td.length;i++){
td[i].addEventListener('click',function(){
for(var i =0;i<td.length;i++){
td[i].className =""
}
var trC = this.parentNode.children
for(var i =0;i<trC.length;i++){
trC[i].className="wrap"
}
for(var i = 0;i<tr.length;i++){
tr[i].children[this.cellIndex].className="wrap"
}
this.className="current"
})
}
}
一开始居然不知道有cellIndex这个属性。。。
function bind() {
var tr = document.querySelectorAll('tr')
var td = document.querySelectorAll('td')
for (var i = 0; i < td.length; i++) {
td[i].addEventListener('click', function () {
for (var i = 0; i < td.length; i++) {
td[i].className = "";
}
var line = this.parentNode.children;
var column = 0;
for (var i = 0; i < line.length; i++) {
if (this == line[i]) {
//定位列数
column = i;
}
line[i].className = "wrap";
}
for (var j = column; j < td.length; j = j + line.length) {
td[j].className = "wrap";
}
this.className = "current";
})
}
} function bind() {
let table = document.getElementsByTagName('tbody')[0];
let m = table.children.length, n = table.children[0].children.length;
let curY, curX;
for(let i = 0; i < m; i ++) {
for(let j = 0; j < n; j ++) {
let curComp = table.children[i].children[j];
if(curComp == event.target) {
curY = i;
curX = j;
}
// 复原
curComp.className = "";
}
}
for(let i = 0; i < n; i ++) {
// 周边
table.children[curY].children[i].className = "wrap";
}
for(let i = 0; i < m; i ++) {
// 周边
table.children[i].children[curX].className = "wrap";
}
table.children[curY].children[curX].className = "current"
} 主要考的是闭包思想,此时i作为函数参数传入立即执行函数,不会随外部i的变化而变化
function bind() {
var td = document.getElementsByTagName("td");
var tr = document.getElementsByTagName("tr");
var m = tr.length;
var n = Math.floor(td.length/m);
for (var i=0;i<td.length;i++){
(function(i){
td[i].onclick = function(){
console.log(i);
for (var k=0;k<td.length;k++){
td[k].className="";
if (k ==i)
td[k].className="current";
else if (Math.floor(k/n)==Math.floor(i/n)||k%n ==i%n){
td[k].className="wrap";
}
}
};
})(i);
}
} function bind() {
consttds = document.getElementsByTagName('td'),
trs = document.getElementsByTagName('tr'),
m = trs.length,
n = Math.round(tds.length / m);
for(let i = 0; i < tds.length; i++) {
tds[i].onclick = () => {
for(let j = 0; j < m * n; j++) {
tds[j].className = '';
if(i == j) {
tds[j].className = 'current';
}
if((Math.floor(j / n) == Math.floor(i / n) || i % n == j % n) && j != i) {
tds[j].className = 'wrap'
}
}
}
}
}