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.

    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭