繁体   English   中英

Javascript onclick事件针对ID触发,但不针对类

[英]Javascript onclick event firing for id but not for class

我对Java语言还很陌生,并且正在尝试获得一种“单击放大”效果,其中单击放大的图像会再次缩小它。 通过将缩略图替换为原始图像来进行放大。 我也想稍后使用来自数据库的图像进行幻灯片播放。

为了做到这一点,我进行了一个测试,在其中替换了表明可以通过类进行扩展的id,并且我还使用了全局变量,以便可以跟踪所使用的url。 不确定这是最佳做法,但我尚未找到更好的解决方案。

第一部分工作正常,我的图像没有任何变化,值也根据“ alert”语句进行了更新。 但是,第二部分,带有该类的那部分永远不会触发。

我在做什么错(除了很可能的许多不良做法)?

如果不是直接更改id(而不是直接更改id(用#image_enlarged等替换.image_enlarged等)),而是要调用第一个函数,即带有id的函数,但会输出更新的id,这很令人困惑。

var old_url = "";

$(function(){

   $('#imageid').on('click', function ()
        {       
        if($(this).attr('class')!='image_enlarged'){
            old_url = $(this).attr('src');
            var new_url =  removeURLPart($(this).attr('src'));
            $(this).attr('src',new_url); //image does enlarge
            $(this).attr('class',"image_enlarged");
            $(this).attr('id',"");
            alert($(this).attr('class')); //returns updated class
            }
        });

   $('.image_enlarged').on('click', function (){
       alert(1); //never triggered
       $(this).attr('src',old_url);
       $(this).attr('class',"");
       $(this).attr('id',"imageid");
   });
});

function removeURLPart(e){
   var tmp = e;
       var tmp1 = tmp.replace('thumbnails/thumbnails_small/','');
       var tmp2 = tmp1.replace('thumbnails/thumbnails_medium/',''); 
       var tmp3 = tmp2.replace('thumbnails/thumbnails_large/','');

   return tmp3;
} 

至于html,这确实很简单:

<figure>
   <img src = "http://localhost/Project/test/thumbnails/thumbnails_small/image.jpg" id="imageid" />
   <figcaption>Test + Price thing</figcaption>
</figure>

<script>
   document.write('<script src="js/jquery-1.11.1.min.js"><\/script>');
</script>
<script type="text/javascript" src="http://localhost/Project/js/onclickenlarge.js"></script>

通过API: http//api.jquery.com/on/

.on()方法将事件处理程序附加到jQuery对象中当前 选定 元素

当您执行$('.image_enlarged').on(...)时,该类没有元素。 因此,该功能未在任何元素中注册。

如果要这样做,则必须在更改类后注册事件。

这是一个基于您的代码的示例: http : //jsfiddle.net/8401mLf4/

但这会多次(每次单击)注册事件,这是错误的。 所以我会做类似的事情:

$('#imageid').on('click', function () {
    if (!$(this).hasClass('image_enlarged')) {
      /* enlarge */
    } else {
      /* restore */
    }
}

JSfiddle: http : //jsfiddle.net/8401mLf4/2/

尝试使用:

addClass('image-enlarged')

代替:

.attr('class',"image_enlarged");

最好的方法是拥有一个小图像类和一个大图像类,它们都包含所需的CSS,然后根据要显示的内容使用addClass()和removeClass。

暂无
暂无

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

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