为了账号安全,请及时绑定邮箱和手机立即绑定

将变量分配给单个表格单元格

将变量分配给单个表格单元格

九州编程 2021-06-29 09:51:52
我正在尝试将图像放入表格中。我有这个工作,如果你点击,你会在可用的选项中循环。但是,计数器与单元格无关,它是一个全局计数器。有没有办法创建一个局部变量来跟踪单个单元格在数组中的位置?我曾尝试为一个单元格创建一个局部变量,但它不起作用。下面是js中的相关函数:var i = 1;var table = document.getElementsByTagName('table')[0];var def = ["tex/white.png", "tex/grass.jpg", "tex/stone.jpg", "tex/water.jpg", "tex/wood.jpg", "tex/lava.jpg"];table.onclick = function(e) {    var target = (e || window.event).target;    if (target.tagName in { TD: 1, TH: 1 }) {        target.className = "img";        console.log((e || window.event).target);        target.setAttribute('style', 'background-image:' + "url(" + def[i] + ")");        if (i < def.length) {            i++        }        if (i == def.length) {            i = 0;        }    }};这是我到目前为止所做的工作的小提琴:https ://jsfiddle.net/6L0armd4/期望的结果是我从单个单元格开始阵列,它只对这些单元格计数。目前,它总是提供下一个纹理,即使我选择了不同的单元格。
查看完整描述

2 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

您需要制作侦听器事件,您可以在下面的代码中将颜色代码更改为您的图像路径,并避免任何本地路径图像链接问题尝试使用在线图像直接链接。


var table = document.querySelector('#table')

var selectedCells = table.getElementsByClassName('selected')


table.addEventListener('click', function(e) {

var td = e.target


if (td.tagName !== 'TD') {

return

}


if (selectedCells.length) {

selectedCells[0].className = ''    

}


td.className = 'selected'

})

table {

 cursor: text;

}

tr {

background-color:white;

}

td {

font-size: 14;

cursor: default;

}


td.selected {

background-color: red;


 // replace this with background image tag like this  

 background-image: url("paper.gif



<table border="1" cellpadding="8" cellspacing="2" id="table">

<tr>

<td>Cell one</td>

<td>Cell Tw</td>

<td>Cell three</td>

<td>Cell Four</td>

<td>Cell five</td>

<td>Cell sex</td>

<td>Cell five</td>

<td>cell seven</td>

<td>cell eight</td>

<td>cell nine</td>

<td>cell tens</td>

<td>cell eleven</td>

<td>cell twelve</td>

</tr>

<tr>

<td>AKo</td>

<td>KK</td>

<td>KQs</td>

<td>KJs</td>

<td>KTs</td>

<td>K9s</td>

<td>K8S</td>

<td>K7s</td>

<td>K6s</td>

<td>K5s</td>

<td>K4s</td>

<td>K3s</td>

<td>K2s</td>


查看完整回答
反对 回复 2021-07-08
  • 2 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信