Javascript onmouseover 和 onmouseout 在以编程方式创建 <img> 时

Javascript onmouseover and onmouseout when creating <img> programmatically

本文关键字:img 创建 方式 onmouseover onmouseout 编程 Javascript      更新时间:2023-09-26

我在Stack Exchange上找到了有关如何为已经存在的图像标签执行此操作的说明,如下所示:

<img src="./img/action_contact.png" onmouseover="this.src='./img/action_contact_hover.png'" onmouseout="this.src='./img/action_contact.png'">

但是如果我以编程方式创建它,如下所示,我无法弄清楚如何正确使用单引号和双引号来编译和运行代码。

$('<img src="./img/action_contact.png" onmouseover="this.src="./img/action_contact_hover.png";" onmouseout="./img/action_contact.png";">')appendTo('#action' + i);
您需要在

属性中的 JS 字符串周围使用转义的单引号(即 ''(。您还缺少appendTo之前的.

$('<img src="./img/action_contact.png" onmouseover="this.src=''hover.jpg'';" onmouseout="this.src=''original.jpg'';">').appendTo('#action' + i);

但是,一种更具可读性的方法是使用 jQuery 的 attr 方法。

$('<img src="./img/action_contact.png">')
    .attr('onmouseover', 'this.src="hover.jpg";')
    .attr('onmouseout', 'this.src="original.jpg";')
    .appendTo('#action' + i);

您甚至可以获得真正的动态,并使用事件委派和数据属性来完全分离内容和功能,并摆脱丑陋的事件属性。

//Create an example image.
var i = 1;//for example
$('<img class="swap" />')
    .attr('src', 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png')
    .attr('data-hoverover', 'https://cdn.sstatic.net/stackexchange/img/logos/se/se-icon.png')
    .attr('data-hoverout', 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png')
    .appendTo('#action' + i);
//Handle swapping.
$(document)
    .on('mouseenter', 'img.swap', function() {
        var $this = $(this);
        $this.attr('src', $this.attr('data-hoverover'));
    })
    .on('mouseleave', 'img.swap', function() {
        var $this = $(this);
        $this.attr('src', $this.attr('data-hoverout'));
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="action1"></div>

你只需要使用 ' 转义一些刻度。

$('<img src="./img/action_contact.png" onmouseover="this.src=''hover.jpg'';" onmouseout="this.src=''original.jpg'';">')appendTo('#action' + i);