为什么代码无法运行?
<body>
<img src="wolfs.jpeg" alt="lol" id="change">
<button id="button">click to change picture</button>
</body>
花了很长时间住在这个
img.addEventListener("click", changeNow);
function changeNow() {
var img = document.getElementById("change");
if (img.src = "../img/backpack.jpeg") {
img.src = "../img/back.jpeg";
} else {
img.src = "../img/backpack.jpeg";
}
}
```的JavaScript
洛尔 ````
答案 0 :(得分:1)
您刚刚在if语句中输了一个拼写错误:if (img.src = "../img/backpack.jpeg")
,您需要===
而不是=
let img = document.getElementById('change');
let button = document.getElementById('button');
button.addEventListener("click", changeNow);
function changeNow() {
var img = document.getElementById("change");
if (img.src === "https://i.pinimg.com/736x/db/63/32/db633275b729187b04859bbca38eb156--yellow-backpack-yellow-outfits.jpg") {
img.src = "http://www.spiritanimal.info/wp-content/uploads/Wolf-Spirit-Animal-2.jpg";
} else {
img.src = "https://i.pinimg.com/736x/db/63/32/db633275b729187b04859bbca38eb156--yellow-backpack-yellow-outfits.jpg";
}
}
&#13;
<body>
<img src="http://www.spiritanimal.info/wp-content/uploads/Wolf-Spirit-Animal-2.jpg" alt="lol" id="change" style="height: 200px; width: 200px">
<button id="button">click to change picture</button>
</body>
&#13;
答案 1 :(得分:1)
Tree t = new Tree(nums[0]);
for (int i = 1; i < nums.Length; i++)
{
t.Add(nums[i]);
}
Console.Write("Tree contents: ");
t.PrintInOrder();
Console.WriteLine();
Console.WriteLine("Tree statistics:");
Console.WriteLine(" Number of nodes: " + t.Count());
var img1 = 'https://cloud.netlifyusercontent.com/assets/344dbf88-fdf9-42bb-adb4-46f01eedd629/68dd54ca-60cf-4ef7-898b-26d7cbe48ec7/10-dithering-opt.jpg';
var img2 = 'https://c1.staticflickr.com/2/1018/805106121_ab84d1a216_b.jpg';
var changePicture = document.getElementById('change_picture');
changePicture.addEventListener("click", changeNow);
function changeNow() {
var img = document.getElementById("image");
if (img.src == img1) {
img.src = img2;
}else{
img.src = img1;
}
}
img{
width: 100px;
height: 100px;
}
答案 2 :(得分:0)
document.getElementById('button').addEventListener("click", changeNow);
function changeNow() {
var img = document.getElementById("change");
if (img.getAttribute("src") === "../img/backpack.jpeg") {
img.setAttribute("src", "../img/back.jpeg");
} else {
img.setAttribute("src", "../img/backpack.jpeg");
}
}
button
id
===
,而不是=
。getAttribute()
和setAttribute()
来操纵src
值。在这里阅读更多内容:
答案 3 :(得分:0)
function changeNow() {
var img = document.getElementById('change');
var toggled = img.getAttribute('data-toggled');
var imgURI = '../img/backpack.jpeg';
if(toggled === '1') {
imgURI = '../img/back.jpeg';
toggled = '0';
} else {
imgURI = '../img/backpack.jpeg';
toggled = '1';
}
img.src = imgURI;
img.setAttribute('data-toggled', toggled);
}