我编写了一个简单的函数,该函数应在2张图像之间交换,单击按钮时应触发此函数,但单击时无反应。
我尝试了addEventListener和onclick方法,但都没有尝试。
<img id="avatar" src="dog1.jpg" alt="avatar">
<button id="button">change dog</button>
function changeDog() {
var dog = document.getElementById('avatar').scr;
if (dog == "dog1.jpg" ) {
document.getElementById('avatar').scr = "dog2.jpg";
}
else {
document.getElementById('avatar').src = "dog1.jpg";
}
}
var button = document.getElementById('button');
button.addEventListener=('click', changeDog);
我希望单击按钮,将id ='avatar'的图像从“ dog1.jpg”更改为“ dog2.jpg”,反之亦然,但是绝对没有任何反应。没有显示错误消息。我怀疑这可能是一个愚蠢的错误,因为我没有经验,但是我对此感到震惊。谢谢大家的帮助。
答案 0 :(得分:2)
您的代码中有一些错字。见下文
function changeDog() {
var dog = document.getElementById('avatar');
if (dog.src === "dog1.jpg" ) {
dog.src = "dog2.jpg";
}
else {
dog.src = "dog1.jpg";
}
}
var button = document.getElementById('button');
button.addEventListener('click', changeDog);
<img id="avatar" src="dog1.jpg" alt="avatar">
<button id="button">change dog</button>
此外,您还应该决定阅读有关比较的内容(使用===代替==): https://www.w3schools.com/js/js_comparisons.asp
答案 1 :(得分:0)
function changeDog() {
// you create a constant for document.getElementById().src, so do not need it every line
const dog = document.getElementById('avatar').src;
if (dog === "dog1.jpg" ) {
dog = "dog2.jpg";
}
else {
dog = "dog1.jpg";
}
}
const button= document.getElementById("button");
button.addEventListener("click", () => {
changeDog();
}
从var更新为let / const(新标准),将您的粗略等值更改为绝对值,并创建了对事件监听器的直接调用,我使用的call方法允许您在changeDog()
之后执行其他操作如果您愿意,也可以。您的原始代码存在一些问题,导致其无法实际运行。
答案 2 :(得分:0)
function changeDog() {
const dog = document.getElementById('avatar');
const imgSrc = dog.src === "dog1.jpg" ? "dog2.jpg" : dog.src;
dog.src = imgSrc;
}
const button = document.getElementById('button');
button.addEventListener('click', changeDog);
<img id="avatar" src="dog1.jpg" alt="avatar">
<button id="button">change dog</button>
答案 3 :(得分:0)
您的代码中存在多个错误。例如,您在某些地方写了src
,在其他地方写了scr
。另外,您一次又一次地重复代码的一部分。
// Array with all dogs. Makes it easier to add more dogs.
const dogs = [ "dog1.jpg", "dog2.jpg" ];
function changeDog() {
// Get the avatar element
const avatar = document.getElementById('avatar');
// Get current name. Note that the broswer probably have added
// the full url to the image. I use split to break up the string
// in an array, and then use slice(-1) to get the last item
// and then [0] to get the element.
const dog = avatar.src.split('/').slice(-1)[0];
// get the index of the dog
const index = dogs.indexOf( dog );
// set the new src, from the dogs array, with the index + 1;
// If index + 1 is larger than the length of the dogs-array
// the % (remainder-operator) will make sure that the index
// wraps around to 0, so we get the next name.
avatar.src = dogs[ ( index + 1 ) % dogs.length ];
console.log( avatar.src );
}
var button = document.getElementById('button');
button.addEventListener('click', changeDog);
<img id="avatar" src="dog1.jpg" alt="avatar">
<button id="button">change dog</button>