jquery - 如何使用 Jquery 使按钮将图像与另一个图像交换?
问题描述
我对 Jquery 很陌生,正在尝试学习它,我的代码似乎有问题,我希望它在单击按钮时更改图像,但图像没有改变。
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.min.js">
$('input').toggle(
function() {
$('img').attr('src', '/images/test1.png');
},
function() {
$('img').attr('src', '/images/test2.png');
}
);
</script>
</head>
<body>
<input value="change image" type="button" />
<img src="test1.png" />
</body>
</html>
解决方案
问题 1
脚本元素加载单个脚本。
这可以来自开始标记和结束标记之间的代码或src
属性指定的 URL 。
它不能同时加载两者。
如果您同时提供两者(正如您所做的那样),src
则将使用该属性并且将忽略内联脚本。
您需要两个脚本元素。一个加载 jQuery 库,一个加载使用该库的脚本。
问题 2
脚本运行时input
,您的文档中没有任何元素。请参阅为什么 jQuery 或诸如 getElementById 之类的 DOM 方法找不到元素?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
$('input').toggle(
function() {
$('img').attr('src', 'https://placeimg.com/150/150/animals');
},
function() {
$('img').attr('src', 'https://placeimg.com/150/150/people');
}
);
});
</script>
<input value="change image" type="button" />
<img src="https://placeimg.com/150/150/animals" />
问题 3
这看起来不像您想要的行为(每次单击某些东西时,切换不会在两个函数之间切换),您可能希望改用单击事件处理程序。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
const one = 'https://placeimg.com/150/150/animals';
const two = 'https://placeimg.com/150/150/people';
$('input').on('click', toggle);
function toggle() {
const current = $('img').attr('src');
$('img').attr('src', current === one ? two : one);
}
});
</script>
<input value="change image" type="button" />
<img src="https://placeimg.com/150/150/animals" />
推荐阅读
- docker - 基于私有 ECR 仓库中的镜像构建 docker 镜像
- google-sheets - 想要将日期添加到某个列时如何在谷歌表格脚本中添加多个目标列
- speech-to-text - 创建项目特定的 Vosk 字典
- reactjs - Axios 等待 axios.get() 在具有多个操作的 useEffect(, []) 序列中不受支持
- linux - 如何通过门户实时跟踪终端的进度?
- javascript - 从javascript输入提示框中返回一个值到C#
- maya - Maya 脚本是否区分大小写?
- aiosmtpd - 接收电子邮件时通过 aiosmtpd 断开连接
- excel - 如何遍历一列并检查该值是否与下一个值匹配然后追加?
- python - 使用 Python3 运行 Excel 宏的最佳方法是什么?