zoukankan      html  css  js  c++  java
  • 一道面试题

    <table id="td">
    <tr>
    <th id=“"sec">第一头</th>
    <th>第二头</th>
    </tr>
    <tr>
    <td>
    <input type="text" name="usr">
    </td>
    <td>
    <input type="button" value="check" onclick="cheng();">
    </td>
    
    </tr>
    </table>
    

    编写cheng()方法,当不输入时,让第一头为红色,再请教很多人之后又了答案

    
    

    function preSibing(obj){
    var x=obj.previousSibling;
    if(x==null){
    return null;
    }
    while(x&&x.nodeType!=1){
    x=x.previousSibling;
    }
    return x;
    }

     

    先得到

    <td>
    <input type="text" name="usr">
    </td>这个td元素

    之前我直接用的this.previousSibling,打印他的nodeName,是#text我开始错误的以为是input的text节点,后来发现是空格

    然后是得到td的第一个子节点,当然不能用firstChild,

    function getFistChild(n){
    
    
        var v=n.childNodes;
        
        //alert(v.length);
    /*var child
        for(child in v){
        
            if(child.nodeType==1){
            //alert(child.nodeName);
            //alert("alert");
                return child;
            }
        }*/
        for(var i=0;i<v.length;i++){
        alert(v[i].nodeType);
        
            if(v[i].nodeType==1){
                return v[i];
            }
        }

    在这个函数中我开始

    var v[]=n.childNodes;一直报错

    得到了input这个节点

    function cheng(obj){
        //alert(obj.previousSibling.nodeName);
        var preTd=preSibing(obj.parentNode);
        var input=getFistChild(preTd);
    
        //var tb=document.getElementById("td");
        //alert("re");
        var thC=document.getElementById("sec");
        
        if(input.value==""){
        alert("ss");
            thC.style.color="red";
        }    
    }

    这样就搞定了

  • 相关阅读:
    mpvue: stylus定义主题色
    mpvue: 单个页面自定义导航栏或隐藏
    mpvue: fsevents is not a constructor
    Nginx:taro h5 Nginx代理配置
    git: 替换remote origin
    taro3.x: h5地图兼容组件封装
    taro3.x: h5地图兼容
    taro3.x: 使用taro-router在H5浏览器返回报错
    taro3.x: tarojs-router
    java线程与线程安全的单例模式
  • 原文地址:https://www.cnblogs.com/bashala/p/3598711.html
Copyright © 2011-2022 走看看