这是一个示例,假设您的标记始终采用相同的格式。
CSS
.imgwk {
height: 45px;
}
HTML
<table id="table01">
<thead></thead>
<tbody>
<tr>
<td id="a01" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpg" />
</button>
</td>
<td id="a02" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpg" />
</button>
</td>
<td id="a03" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpgg" />
</button>
</td>
<td id="a04" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpg" />
</button>
</td>
<td id="a05" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpg" />
</button>
</td>
<td id="a06" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpgg" />
</button>
</td>
<td id="a07" bgcolor="brown">
<button type="button" name="blabla">
<img class="imgwk" name="wknight" src="http://thumb1.shutterstock.com/thumb_small/98550/98550,1278941506,3/stock-photo-white-chess-knight-56993335.jpg" />
</button>
</td>
</tr>
</tbody>
</table>
Javascript
function getImgSrc(tableID, tdId) {
var table = document.getElementById(tableID),
tds = table.getElementsByTagName("td"),
img,
src;
Array.prototype.some.call(tds, function (td) {
if (td.id === tdId) {
img = td.getElementsByTagName("img");
if (img && img.length) {
src = img[0].src;
return true;
}
}
return false;
});
return src;
}
function setImgSrc(tableID, tdId, src) {
var table = document.getElementById(tableID),
tds = table.getElementsByTagName("td"),
img;
Array.prototype.some.call(tds, function (td) {
if (td.id === tdId) {
img = td.getElementsByTagName("img");
if (img && img.length) {
img[0].src = src;
return true;
}
}
return false;
});
return src;
}
alert(getImgSrc("table01", "a07"));
setImgSrc("table01", "a07", "http://img135.imageshack.us/img135/8067/daciathaliabe5.jpg"
);
在jsfiddle 上
注意事项:
使用 ID 而不是 NAME 作为 ID 必须是唯一的,而 NAME 则不然。这可能与您的标记相关,也可能不相关,具体取决于具体情况。
使用 CSS 类而不是内联样式:内联样式与类
这种选择方法不是获得所需结果的唯一方法,您还可以使用document.querySelectorAll或jquery等外部库