javascript - 为什么我的js代码没有报错,但是网页中显示不出效果
PHP中文网
PHP中文网 2017-04-11 12:16:46
[JavaScript讨论组]

js代码没有出现错误,但是网页中没有预想的效果
html



    
        Image Gallery
        
        
    
    
     

Snapshots

my image gallery

Choose an image.

js代码

window.onload = prepareGallery;
function prepareGallery(){
    if(!document.getElementsByTagName)
    {return false;}
    if(!document.getElementById)
    {return false;}
    if(!document.getElementById("imageGallery"))
    {return false;}

    var gallery = document.getElementById("imageGallery");
    var links = gallery.getElementsByTagName("a");
    for(var i = 0;i < links.length;i++){
        links[i].onclick = function(){
           return !showPic(this);
      }
    }
}
function showPic(whichpic){
    if(!document.getElementById)
    {return false;}
    var source = whichpic.getAttribute("href");
    if(!document.getElementById.getElementById("placeholder"))
    {return false;}
    var placeholder = document.getElementById("placeholder");
    if(placeholder.nodeName != "IMG")
    {return false;}
    placeholder.setAttribute("src",source);
    if(document.getElementById("description"))
    {
        if(whichpic.getAttribute("title")){
        var title = whichpic.getAttribute("title");
        }else{
            title = "";
        }
    var description = document.getElementById("description");
    if(description.firstChild.nodeType == 3){
    description.firstChild.nodeValue = title;
    }
   }
    return true;
}
PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
迷茫
document.getElementById.getElementById("placeholder")

点击后,此处有报错

PHPz
for(var i = 0;i < links.length;i++){
    links[i].onclick = function(e){
       e.preventDefault();//这里阻止事件的默认行为,防止a链接导致页面刷新
       return !showPic(this);
  }
}
  1. 阻止事件的默认行为

  2. 这些document.getElementById等等的验证是没多大必要,而且容易出错

if(!document.getElementById.getElementById("placeholder"))//这里就重复了
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号