weixin_33714884 2017-04-25 15:37 采纳率: 0%
浏览 36

JS AddEventListener问题

My goal here is to take an example from my book that displays different book covers upon button presses. The new part I need to add is to add an event listener that displays the title of the book when you hover over an image.

Note** I am using the title attribute to achieve showing the title when hovering, but I have to have the title text display under the book that has been hovered over

Why won't this work?

         document.addEventListener("mouseover", function(){
document.getElementById("image").innerHTML = title;
});

I've included a link to my website as that would be easier than pasting all of the code. I am very new to using the DOM and AJAX in general. I'm not looking for any answers, just some help on understanding what I may be doing wrong.

http://ualr.edu/gawalker1/16%20CH%20HW/PullImagesOntoPage.html

  • 写回答

2条回答 默认 最新

  • local-host 2017-04-25 15:54
    关注

    What you're trying to do, I think, is event delegation. In order to do that, you have the right idea to listen on the parent element, like

    document.addEventListener("mouseover", function(e){ ... });
    

    (You must capture the event object, passed in as the first argument of the event listener function, which I've named e here.)

    What you want to do is look at e.target, which is the element within document currently targeted by the mouseover event, and use its title property.

    document.addEventListener("moveover", function(e) {
        if(e.target && e.target.nodeName == "IMG") {
            document.getElementById("image").innerHTML = e.target.title;
        }
    });
    

    This will check the mouse has entered an <img> element, and if so, it will set innerHTML of the element with id="image" (which is currently missing from your page, but I assume you'll add it, or chose another ID that does exist on the page).

    If you later have other images you don't want this behavior to apply to, you can either choose a more selective parent than the whole document, or add more conditions to the filtering if condition, like ... && e.target.class == "hover-target" to limit the behavior to images with a particular class.

    评论

报告相同问题?