gpt4 book ai didi

javascript - 如何修复仅返回 else 语句的 if 函数

转载 作者:行者123 更新时间:2023-11-30 14:03:14 26 4
gpt4 key购买 nike

我正在编写一个函数,该函数应根据图像的 src 在区域中显示特定文本。当鼠标悬停在另一个图像上时,此函数运行。图片旁边始终显示相同的文本。

我试过 if-else 函数,onmouseover 或 addEventListener 都不起作用。

<img id="avatar" src="avatar1.jpg" alt="avatar" class="avatar">
<img src="icon.jpg" class='icon' id='icon'>
<p id='description'> specifit text should appear in here <p>
/* this function changes the source of 'avatar' and it works fine */

const faces = ["avatar1.jpg", "avatar2.jpg"];
const avatar = document.getElementById('avatar');

function changeFace() {
const face = avatar.src.split('/').slice(-1)[0];
const index = faces.indexOf(face);

avatar.src = faces[(index + 1) % faces.length];
console.log(avatar.src);
}

var icon = document.getElementById('icon');
icon.addEventListener('click', changeFace);

/* clicking on the 'icon' changes the src of 'avatar' from 'avatar1.jpg' to 'avatar2.jpg' and vice versa. */

/*this function display 'text' in p 'description', it works fine*/

function writeText(text) {
document.getElementById("description").innerHTML = text
}

/* this is the function that doesn't work */

function changeText() {
if (avatar.src === "avatar1.jpg") {
writeText('text number 1');
} else {
writeText('text number 2');
}
}

icon.addEventListener('mouseover', changeText);

无论'avatar'的src如何,它都会返回'text number 2'

最佳答案

您需要更改为 if (avatar.getAttribute('src') === "avatar1.jpg") 而不是 avatar.src

.src 返回完全限定的绝对 URL,即使 HTML 中的内容是相对 URL。 getAttribute() 返回 DOM 元素的确切属性

/*this funcion changes the source of 'avatar' and it works fine*/

const faces = [ "avatar1.jpg", "avatar2.jpg" ];
const avatar = document.getElementById('avatar');

function changeFace() {
const face = avatar.src.split('/').slice(-1)[0];
const index = faces.indexOf( face );

avatar.src = faces[ ( index + 1 ) % faces.length ];
console.log( avatar.src );
}

var icon = document.getElementById('icon');
icon.addEventListener('click', changeFace);

/*clicking on the 'icon' changes the src of 'avatar' from 'avatar1.jpg' to 'avatar2.jpg' and viceversa.*/

/*this function display 'text' in p 'description', it works fine*/

function writeText(text) {
document.getElementById("description").innerHTML=text
}

/*this is the funcion that doens't work*/

function changeText() {
console.log(avatar.getAttribute('src'))
if (avatar.getAttribute('src') === "avatar1.jpg") {
writeText('text number 1');}
else { writeText('text number 2');}
}

icon.addEventListener('mouseover', changeText);
<img id="avatar" src="avatar1.jpg" alt="avatar" class="avatar">
<img src="icon.jpg" class='icon' id='icon'>
<p id='description'> specifit text should appear in here <p>

关于javascript - 如何修复仅返回 else 语句的 if 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com