dongxingdu9594 2012-08-27 12:36
浏览 52
已采纳

如何在此函数中实现正确的show hide / slideToggle功能

I have a function in jquery which displays images on link click and also has to hide the image when the link is clicked again.

This is the code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
    var $j = jQuery.noConflict();
    $j(document).ready(function(){
        $j('.links').click( function(){
        var linkclicked = this.id;
        var url = $j(this).attr('href'),
        image = new Image();

        image.src = url;
        image.onload = function () {
              $j('#image-holder'+linkclicked).empty().append(image);
            /* The above line shows the image on first click.
               Adding slideToggle hides the image again  */
            };
            image.onerror = function () {
                $j('#image-holder'+linkclicked).empty()
                                .html('That image is not available.');
            }
            $j('#image-holder'+linkclicked).empty().html('Loading...');
            return false;
        });
    }); 
function loadnow() {

}
</script>
</head>
<body>
<?php $topicid=1; ?>
<a href="myimages/red-brick-wall-texture.jpg" class="links" id="<?php echo $topicid; ?>" >Show image</a>
<div id="<?php echo 'image-holder'.$topicid; ?>"></div>
<?php $topicid=2; ?>
<br><a href="/myimages/gymicon.JPG" class="links" id="<?php echo $topicid; ?>" >Show image</a>
<div id="<?php echo 'image-holder'.$topicid; ?>"></div>
</body>
</html>

Please let me know where to write slideToggle as to enable show/hide function properly. There are two links here which show separate images. They are shown when clicked but the problem is to hide them on next click and make them
visible when clicked again and so on.

  • 写回答

1条回答 默认 最新

  • dqnk57224 2012-08-27 13:02
    关注

    The way you have your code here is not really quite right for .slideToggle. You should not put the URL for the image in the href attribute of an <a> element because the link will try to go there on click.

    The way .slideToggle works is well documented on the docs page. All you have to do is use the HTML <img> tag, which is made to hold images. Then you $().hide(); them when the page loads so they aren't shown. All you have to do them is call the .slideToggle() function on the link click event.

    See the working example with some misc pictures in this fiddle: http://jsfiddle.net/8xcZT/5/.

    Or here is a working version of your code: http://jsfiddle.net/JMXba/9/. I can see this may be desirable to wait for the click to load the image.

    Good Luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置