我想更改html中表格的单个单元格的图像源


<tr><!-- 8 -->
<td id = "8A"><!-- A -->
<img src="Media/empty_square_white.png" height="160px" width ="160px">
</td>
...
<script>
function changeSource(){
document.getElementById("8A").src="empty_square_brown.png";
}
</script>
<button onclick="changeSource">change</button>

这就是我想要做的,但是当我按下按钮时似乎什么都没有发生。我也试过在没有按钮的情况下这样做,但是似乎也不起作用,我也使用内部CSS定义了id。由于

您的id引用周围的td,它没有属性src。您需要在img元素或子元素的引用上设置id。

还有你的新值"empty_square_brown.png"丢失了在原始源"Media/"中设置的路径。onclick调用需要函数括号。这里有一些工作示例。使用title属性来显示效果。

<tr><!-- 8 -->
<td><!-- A -->
<img id="8A" src="Media/empty_square_white.png" height="160px" width ="160px" title="empty_square_white.png">
</td>
...
<script>
function changeSource(){
document.getElementById("8A").src="Media/empty_square_brown.png";
document.getElementById("8A").title="empty_square_brown.png";
}
</script>
<button onclick="changeSource()">change</button>

你可以试试这个

function changeImg(){
document.getElementById("image").src = "https://images.unsplash.com/photo-1581618048854-b2f6f877cef3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"
}
img{
width:50px;
height:50px;
}
<table border=1>
<tr>
<td >
<img id="image" src="https://images.unsplash.com/photo-1626285094808-143d7bb02f14?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80" alt="" onclick="changeImg()">
</td>
<td>
<img src="#" alt="">
</td>
</tr>
</table>

最新更新