简体   繁体   English

使用jQuery将鼠标悬停事件附加到img中的img

[英]Append mouseover event to img in a div with jQuery

I am trying to append a mouseover event to an image in a div with jQuery. 我正在尝试将jQuery鼠标悬停事件附加到div中的图像上。 Here is how I append the imgs to the div. 这是我将img附加到div的方法。 This is my code, appending the img and the href to the div. 这是我的代码,将img和href附加到div。 Now, I want the mouseover. 现在,我要把鼠标悬停在上面。 So far I have tried a lot of things, which simply did not work, like trying to append a function ... 到目前为止,我已经尝试了很多事情,但是根本没有用,比如尝试附加一个函数……

for (var index in obj){                 
    $("#my_div").append($("<a>", 
    {
        href: urlSite, 
        html: $("<img>", { src: avatar }),
    }));
}

You can use the jquery on function to add handlers to events like so 您可以使用jquery on函数将处理程序添加到此类事件中

$('#your_image_id').on('mouseover', function() {
    console.log('hello');
});

Edit 编辑

To do it dynamically: 要动态地执行此操作:

$('#my_div').append($('<img>').attr('src', avatar).on('mouseover', function() {
    console.log('hello');
}));

Edit2 编辑2

for (var index in obj){                 
    $("#my_div").append($("<a>", 
    {
        href: urlSite, 
        html: $("<img>", { src: avatar }),
    }).mouseover(function() {
        $('#my_other_div').append($(this).attr('href')); 
    })); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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