【问题标题】:Cannot change the image src for event.target images无法更改 event.target 图像的图像 src
【发布时间】:2021-10-06 19:05:49
【问题描述】:
<div class = "category_list_11">
            <img src = "./static/images/compre6.png" class = "coffeeimages">
            <div class = "category_list_field">
                <div class = "category_list_field1">
                    <button class = "categoryfieldbutton1">
                    <img src = "./static/images/hm_favorite_2.png" class = "favorite_img1">
                    </button>
                </div>
                <div class = "category_list_field2">
                    <button class = "categoryfieldbutton2">
                    <img src = "./static/images/hm_2_cart_2.png" class = "favorite_img2">
                    </button>
                </div>
            </div>
        </div>

在 javascript 中,我尝试为 category_list_field_1 添加事件监听器

var categoryfields = Array.from(category_list_field);

for (let i = 0; i < categoryfields.length; i++) {

categoryfields[i].addEventListener("click", event => {

console.log(event.target.matches(".favorite_img2"))
if(event.target && event.target.matches(".favorite_img2")) {

console.log(event.target.src);

if (event.target.src = "static/images/hm_2_cart_2.png") {

console.log("1");
event.target.src = "static/images/hm_2_cart_2_a.png";
console.log(event.target);

}

if (event.target.src = "static/images/hm_2_cart_2_a.png") {

event.target.src = "static/images/hm_2_cart_2.png";

}

我想创建一个事件监听器,它可以让“favorite_img2”类的图像在单击时将 src 更改为“hm_2_cart_2_a.png”,然后在下次单击时返回到上一个 src。线

console.log(event.target);

给出输出&lt;img src="static/images/hm_2_cart_2.png" class="favorite_img2"&gt;

对不起,可怕的格式。 非常感谢您。

【问题讨论】:

  • 缺少大括号和分号,更不用说痛苦的缩进了。下次扔beautifier.io ????
  • @asyncawait 哦,非常感谢您提供的非常有用的提示!从现在开始会确保使用它

标签: javascript events


【解决方案1】:

你的问题很可能是这一行

if (event.target.src = "static/images/hm_2_cart_2.png") 

在括号内应该有一个比较运算符,而不是分配.src,这将始终为真。您需要使用双等号 == 将 src 与字符串进行比较。

【讨论】:

  • 哦,原来如此!哇,这很尴尬:D
  • 很高兴为您提供帮助,一旦您看到答案,总是很容易。我没有做太多测试,所以可能还有其他问题。我也鼓励您探索code review。可以做很多事情来清理你的代码,我认为这些事情与这个答案无关。编码愉快!
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 2019-03-15
相关资源
最近更新 更多