英文:
Can't change image source of element ID when using variable name instead of string
问题
我正在编写一个函数,根据传递给函数的两个字符串来更改图像的来源,a
是元素的 ID,b
是图像的新来源。
在这个实例中,我已确认两个变量正确地传递给函数。
console.log(a);
是 layerAddButton
console.log(b);
是 images/layerAdd-blue.svg
这是我的代码:
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
这并未像预期那样改变图像的 URL,而是在 Chrome 中出现错误:
> functions.js:3025 Uncaught TypeError: Cannot set properties of null
> (setting 'src')
> at swapImg (functions.js:3025:32)
> at HTMLButtonElement.onmouseleave (app.htm:1132:274)
当我像这样硬编码时,它可以正常工作:
document.getElementById('layerAddButton').src = 'images/layerAdd-blue.svg';
英文:
I am writing a function to change the src of an image based on two strings passed to the function, a
, which is the element ID, and b
, which is the new source for the image.
In this instance, I have confirmed that both variables are passed to the function correctly.
console.log(a);
is layerAddButton
console.log(b);
is images/layerAdd-blue.svg
Here is my code :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
This does not change the url of the image as expected, but gives an error in chrome :
> functions.js:3025 Uncaught TypeError: Cannot set properties of null
> (setting 'src')
> at swapImg (functions.js:3025:32)
> at HTMLButtonElement.onmouseleave (app.htm:1132:274)
This works fine when I hard code like so :
document.getElementById('layerAddButton').src = 'images/layerAdd-blue.svg';
答案1
得分: 1
我尝试过,它有效。确保在将其传递给函数时正确编写 Id。同时确保脚本位于元素之后的 HTML 中,而不是在头部。
英文:
I tried it and it works. Make sure to write the Id correctly when passing it to the function. And make sure the script is in the HTML after the element and not in the head.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<img
src="https://www.testingtime.com/app/uploads/2017/07/Grundregeln_fuer_User_Testing-750x500.jpg"
alt=""
id="imgElement"
/>
<body>
<script>
function swapImg(id, url) {
var a = id;
var b = url;
console.log(document.getElementById(a));
document.getElementById(a).src = b;
}
swapImg("imgElement", "https://source.unsplash.com/random");
</script>
</body>
</html>
答案2
得分: 0
为了修复这个问题,你只需要将变量传递给getElementById()函数,而不仅仅是变量名称。
正确的代码应该是:
function swapImg(id, url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
英文:
To fix this, you just needed to pass the variable to the getElementById() function and not just the variable name.
The correct code should be :
function swapImg(id,url)
{
var a = id;
var b = url;
document.getElementById(a).src = b;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论