【发布时间】:2014-11-02 22:25:41
【问题描述】:
我是 Javascript 的新手,我正在尝试获得一种“点击放大”的效果,点击放大的图像会再次缩小它。通过用原始图像替换缩略图来进行放大。我还想稍后使用我数据库中的图像制作幻灯片。
为了做到这一点,我做了一个测试,我用一个类替换了表示可以放大的 id,并且我还使用了一个全局变量,以便我可以跟踪我正在使用的 url。不确定这是最佳做法,但我还没有找到更好的解决方案。
第一部分工作正常,我的图像更改没问题,值也根据“警报”语句更新。但是,第二部分,具有类的部分永远不会触发。
我做错了什么(除了很可能的许多不良做法)?
如果我不更改类,而是直接更改 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>
【问题讨论】:
-
您粘贴的 html 不包含包含该类的图像?
-
tag image_enlarged with class, not found in your html!
-
呃,这个标签应该是javascript添加的,第一次点击后,所以不在html中。
标签: javascript jquery html onclick image-enlarge