zoukankan      html  css  js  c++  java
  • jQuery判断提取的id是否存在

    今天在做练习的时候遇到一种情况,需要给div元素动态添加id名,比如第一种情况id为test1,第二种情况id为test2:

    <div id="test2">test</div>
    
    <script>
    	console.log($("#test1"));
    </script>
    

      此种情况下,jQuery提取id为test1的元素进行操作时,虽然并没有实际对应的id,但操作也会生效。

      因为jQuery提取返回的是一个空的对象object:

                                                     

      比较常用的方法可以用 :$("#id").length 来判断是否存在

    <body>
    <div id="test1">test</div>
    
    <script>
    	console.log($("#test1").length);
    </script>
    </body>
    

      此时如果该id存在,

      $("#test1").length就等于1

                                                        

    这样我们根据id操作就不会出现bug了:
    <div id="test1">test</div>
    
    <script>
    	if($("#test1").length>0){
    		alert("true");
    	}else{
    		alert("false");
    	}
    </script>
    

      

  • 相关阅读:
    python的logging库
    python的os库
    python的setup和teardown
    CF339D Xenia and Bit Operations线段树
    poj3311Hie with the Pie状压dp
    poj3254Corn Fields状压Dp
    CF414BMashmokh and ACMDP
    母函数6连杀
    母函数hdu1085
    UVA 1401Remember the WordDp
  • 原文地址:https://www.cnblogs.com/rose1324/p/8643221.html
Copyright © 2011-2022 走看看