JavaScript 图片库改进

JavaScript 图片库改进

平隐退化

在没有javascript支持的情况下,是否网页会出现错误?

JavaScript和HTML分离

剥离页面元素与用户的逻辑操作,提供页面挂钩

Fn-prepareGallery

现在,需要编写一个简短的函数把有关操作关联到onc1ick事件上我将其命名为 prepareGallery。

下面是我想让这个函数完成的工作。
口检查当前浏览器是否理解 getElementsBy TagName
囗检査当前浏览器是否理解 getelementById。
口检查当前网页是否存在一个d为 imagegal lery的元素。
口遍历 imagegallery元素中的所有链接。
口设置 onclick事件,让它在有关链接被点击时完成以下操作:
■把这个链接作为参数传递给 showPic函数;
■取消链接被点击时的默认行为,不让浏览器打开这个链接

function preparGallery(){
  //检查是否支持get
  if(!document.getElementsByTagName || !document.getElementById){
    return false
  }
  var imgGallery = document.getELementById("gallery");
  if(!imgGallery){
    console.log('浏览器不支持获取id,请启用JavaScript')
    return false
  }else{
    var aContent = imgGallery.getElementsByTagName('a');
    for(var i in aContent){
      if(aContent[i].href){
        this.click = function(e){
          e.preventDefault();
          showPic(this)
          return false
        }
      }

    }
  }
}
//启用事件
window.onload = function(){
  //fn1
  //fn2
  ...
  //fn[n]
}
//快速添加页面onload事件
  function addEventAfterOnload(func){
    var wonload = window.onload
    if(typeof window.onload != 'function'){
      window.onload = func;
    }else{
      window.onload = function(){
        wonload();
        func();
      }
    }
  }

  addEventAfterOnload(func1)

三目运算符

var result = condition ? result1 : result2 ;
//结果为true返回result1

TIPS

element.nodeName 返回值为大写字母

评论