zoukankan      html  css  js  c++  java
  • 如何判断一个对象是Element?

    群里有个人问这么判断一个对象是Element?

    我查了下 

    //underscore.js的实现

    _.isElement = function(obj) {
      return !!(obj && obj.nodeType == 1);
    };

     //valentine.js的实现

    , ele: function (el) {
    return !!(el && el.nodeType && el.nodeType == 1)
    }

     //prototype.js的实现

    isElement: function(object) {

      return object && object.nodeType == 1
    }

    显然isElement({nodeType:1})这样就不行了

    好像没有特别严谨的方法,gg了一下,稍作修改,我的isElement是这样的:

     1 <!doctype html>
     2 <head>
     3 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     4 <title> </title>
     5 </head>
     6 <body>
     7 <script> 
     8 var isElement=+'\v1'?
     9     function (obj){
    10         return obj instanceof Element
    11     }:
    12     function (obj){
    13          return obj && obj.nodeType === 1 && obj.tagName !== undefined
    14     };
    15     
    16     //测试
    17     if (typeof console==='undefined') {
    18         console={
    19             log:function (a){
    20               alert(a);
    21             }
    22         }
    23     }
    24     console.log(isElement(document.createElement('a'))); //true
    25     console.log(isElement(document.createElement('li'))); //true
    26     console.log(isElement(document.createElement('z'))); //true
    27     console.log(isElement(document.documentElement)); //true
    28     console.log(isElement(window)); //false
    29     console.log(isElement({nodeType:1,tagName:2})); //ie true
    30 </script>
    31 
    32 </body>
    33 </html>
  • 相关阅读:
    yml 配置文件注入
    STS 自动生成 getter 和 setter
    maven build 失败
    navicat 使用
    STS 设置 注解提示
    windows下安装Mysql
    安装 mysql
    用Navicat Premium 操作MySQL数据库
    渐变显示渐变消失的BackgroundView
    基于dispatch_after封装YXTimer
  • 原文地址:https://www.cnblogs.com/zhuzf/p/2471854.html
Copyright © 2011-2022 走看看