Javascript 删除onclick函数
我目前正在为一个项目创建一个新的图像滑块,但有一个问题。任务是在页面上显示一个图像,以打开完整大小的onclick。但是,我想让函数消失,图像再次单击返回原始状态 这是我的密码:Javascript 删除onclick函数,javascript,jquery,Javascript,Jquery,我目前正在为一个项目创建一个新的图像滑块,但有一个问题。任务是在页面上显示一个图像,以打开完整大小的onclick。但是,我想让函数消失,图像再次单击返回原始状态 这是我的密码: <html> <head> <title>Fullscreen</title> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head>
<html>
<head>
<title>Fullscreen</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<img src="//path" onClick="full()" id="image" />
<script type="text/javascript">
function full() {
$(function () {
$('#image').on('click', function () {
$(this).width(1000);
});
});
}
</script>
</body>
</html>
全屏
函数满(){
$(函数(){
$('#image')。在('click',函数(){
$(此)。宽度(1000);
});
});
}
图像以较大的状态打开,这很好,但是如何实现第二个onclick函数来删除第一个呢
谢谢你的帮助 你真正想要的是:
下面的代码向您展示了如何实现您的实际要求:
全屏
$(文档).ready(函数(){
$('#image')。在('单击',函数()上){
$(本)
.宽度(1000)
.off('单击')
.on('单击',函数()){
$(本)
.宽度(“”)
.off('click');
});
});
});
另请参阅,以获得一个有效的演示
您可能想要的: 您可能需要的只是一个单击处理程序,用于切换图像的宽度 最好的方法是这样:
<html>
<head>
<title>Fullscreen</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<img src="//path" id="image" />
<script type="text/javascript">
$(document).ready(function() {
$('#image').on('click', function() {
var me = $(this);
me.width(me.width() !== 1000 ? 1000 : '');
});
});
</script>
</body>
</html>
全屏
$(文档).ready(函数(){
$('#image')。在('单击',函数()上){
var me=$(此);
me.width(me.width()!==1000?1000:“”);
});
});
另请参见工作演示。获取先前指定使用的事件
$('#image').off('click')
要缩小图像,请使用
var size = 0;
function full() {
$(function () {
$('#image').on('click', function () {
if (size === 0) {
size = $(this).width();
$(this).width(1000);
} else {
$(this).width(size);
size = 0;
}
});
});
}
如果宽度为
1000px
,则将其移除,否则将其设置为1000
,如下所示
<img src="//path" id="image" />
<script type="text/javascript">
$('#image').on('click', function () {
if ($(this).width() == '1000')
$(this).width('');
else
$(this).width(1000);
});
</script>
$('#image')。在('click',函数(){
如果($(this).width()
$(此).width(“”);
其他的
$(此)。宽度(1000);
});
您不需要删除onclick侦听器,但需要修复一些问题。您有一个内联onclick回调函数,它实际上调用了full
函数,该函数反复附加一个新的click侦听器,最终导致click处理程序被调用2^n次
您只需在代码中保留一个,并在其中检查图像的当前宽度,以便选择单击图像时发生的情况(假设50px是起始宽度):
$('#image')。在('click',function()上{
$(this).width($(this).width()!=1000?1000:50);
});代码>
img{
宽度:50px;
过渡:宽度0.2s线性;
}
使用类
和切换类
function full() {
$(function () {
$('#image').on('click', function () {
$(this).toggleClass('changeWidth');
});
});
}
是否要删除事件监听器或在第二次单击时缩小图像?我想将图像还原为原来的样子,因此我猜这将是删除事件监听器删除事件监听器不会还原您对图像所做的操作。它只是将事件从触发回调函数的过程中移除。我认为,没有必要在单击处理程序中包含$(function(){…})
。在函数执行的那一刻,DOM已经加载了。Patrick,你有什么建议吗?就是这样!非常感谢你!我想我需要一个else语句,但我写它的方式对我没有好处。你太棒了,谢谢你,先生。
function full() {
$(function () {
$('#image').on('click', function () {
$(this).toggleClass('changeWidth');
});
});
}