gpt4 book ai didi

以编程方式创建 时的 Javascript onmouseover 和 onmouseout

转载 作者:行者123 更新时间:2023-11-30 17:07:53 25 4
gpt4 key购买 nike

我在 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);

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

//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> 时的 Javascript onmouseover 和 onmouseout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com