简体   繁体   中英

Event returns [object MouseEvent] rather than the text

I have my p tag which suppose to chage text when I trigger mouseover event but somehow I got [object MouseEvent] in return and not the text.

HTML

    <p id="album-name-1"
      onmouseover="changeText('follow me around, greatest song of the album!')">
      change the text
    </p>

JS

      var par = document.querySelector("#album-name-1");

      par.addEventListener("mouseover", changeText);

      function changeText(text) {
        if (this.id === "album-name-1") {
          par.innerHTML = text;
        }
      }

I wanted to do this with the use of the "this" keyword, but somehow it's not working as I expect it to work. Any suggestions?

It's because you're adding a mouseover event listener with addEventListener , and the first parameter of the callback is the event.

Instead, you can pass this as a parameter inside the onmouseover attribute.

 var par = document.querySelector("#album-name-1"); function changeText(elem, text) { if (elem.id === "album-name-1") { par.innerHTML = text; } }
 <p id="album-name-1" onmouseover="changeText(this, 'follow me around, greatest song of the album!')"> change the text </p>

Don't use event attributes. They are full of hard to debug quirks and will bite you someday.

Instead, if you really want to have that text in the markup, store it in a data- attribute and retrieve it from your event handler, that you attached through addEventListener .

 var par = document.querySelector("#album-name-1"); par.addEventListener("mouseover", changeText); function changeText(evt) { // first param is the Event object if (this.id === "album-name-1") { // 'this' is the current target // all the data- attributes of our element // are stored in its.dataset property par.innerHTML = this.dataset.text; } }
 <p id="album-name-1" data-text="follow me around, greatest song of the album!"> change the text </p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM