jQuery的index()原生js实现以及删除空白文本节点函数

funtion findIndex ( elem, array, i ){//实现jQuery.inArray()方法
  var len;
      if ( array ) {
          if ( indexOf ) {
              return indexOf.call( array, elem, i );
          }
          len = array.length;
          i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
          for ( ; i < len; i++ ) {
              if ( i in array && array[ i ] === elem ) {
                  return i;
              }
          }
      }

      return -1;
}

function index( elem ) {
  if ( !elem ) {
  //首先,获取满足选择器的第一个元素,然后获取第一个元素前面的所有的同级元素的个数
    if ( this[0] && this[0].parentNode ) {
      var parentnode = this[0].parentNode,
          node = this[0].previousSibling,
          count = 0;
      if(node != NULL){
        for(var i = 0; node != NULL; ++i ){
          node = node.previousSibling;
          ++count;
        }
      }
      return count;
    }else{
      return -1;
    }
    return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
  }
  if ( typeof elem === "string" ) {
    //如果指定参数为string
    return findIndex( this[0], jQuery( elem ) ,0);
  }
// dom对象或者jQuery对象
  return findIndex( elem.jquery ? elem[0] : elem, this ,0);
// If it receives a jQuery object, the first element is used
//如果是jQuery对象作为参数,那么获取参数第一个对象在调用选择器中的位置!
}

如果需要去掉节点中的空白节点,则加一个删除空白节点的函数即可

function cleanWhitespace(oEelement)//定义一个删除空白节点的函数
{
 for(var i=0;i

你可能感兴趣的:(web,JavaScript,前端,javascript)