I want to write a jquery that by a mouseover change the contain of the first <ul>
, the first <ul>
by default contains 111
and when the mouse is over aaa
appears 111
, bbb
appears 222
, ccc
appears 333
const firstul = document.getElementById('span_Lan');
const boxLi = document.getElementById('ul_box').children;
for (let i = 0; i < boxLi.length; i++) {
boxLi[i].addEventListener('mouseover', () => {
firstul.value += boxLi[i].textContent;
if (boxLi[i].id == "lnk1") firstul.value += "111";
else if (boxLi[i].id == "lnk2") firstul.value += "222";
else if (boxLi[i].id == "lnk2") firstul.value += "333";
})
}
<div>
<ul>
<li id="li_box"> <span id="span_Lan"></span></li>
</ul>
<ul id="ul_box">
<li><a id="lnk1" class="">aaa</a></li>
<li><a id="lnk2" class="">bbb</a></li>
<li><a id="lnk3" class="">ccc</a></li>
</ul>
</div>
3
Answers
There’s a few issues with your code
innerText
orinnerHtml
instead ofvalue
boxLi[i]
Also this isn’t jQuery
To make your code a bit more readable, you should use
querySelectorAll
to select the links. Then run over the elements withforEach
to add aneventListener
per element.In the example below I have created a function called handleMouseOver. This function expects an id as a parameter, which is the id of the listitem.
The function then fires a switch statement to determine which text belongs to this ID. This text is then applied to your span_Lan element.
I also call the function once when initiating the script, to fill in the default value (namely 111).
You said using jQuery , so no need to loops and addEventListener , all you need is just specifying displayed data inside link using data attribute (like data-text in below snippet )
use the hover listener then access current hovered by using
$(this)
key word , then display the data , that’s allSee below snippet :