当前位置:Gxlcms > JavaScript > jquery判断元素内容是否存在

jquery判断元素内容是否存在

时间:2021-07-01 10:21:17 帮助过:7人阅读

这次给大家带来jquery判断元素内容是否存在,jquery判断元素内容是否存在的注意事项有哪些,下面就是实战案例,一起来看一下。

input 用val();

var value = $('#test').val();

是否为空的判断方法:

if(value.length == 0){} 如果value为空执行的操作

if(value!=''){} 如果value不为空执行的操作

jQuery验证文本框内容不为空

通过$.fn 扩展jQuery方法

  1. /**
  2. * 校验文本是否为空
  3. * tips:提示信息
  4. * 使用方法:$("#id").validate("提示文本");
  5. * @itmyhome
  6. */
  7. $.fn.validate = function(tips){
  8. if($(this).val() == "" || $.trim($(this).val()).length == 0){
  9. alert(tips + "不能为空!");
  10. throw SyntaxError(); //如果验证不通过,则不执行后面
  11. }
  12. }

html元素用html();

var value = $('#test').html();

是否为空的判断方法:

if(value.length == 0){

也可以通过判断是说有没有子节点?对于html获取的方法可用

$('#list').children().length === 0 。

方法一

  1. <script type="text/javascript" src="http://m.jb51.net/skin/mobile/js/jquery.min.js"></script>
  2. <p><ul id="thelist2">
  3. <li><a href="https://m.jb51.net/game/140209.html"><img src="//files.jb51.net/do/uploads/litimg/140228/100331632c.jpg">天天飞车航哥破解版</a><em class="xj star5"></em></li>
  4. <li><a href="https://m.jb51.net/game/143515.html"><img src="//files.jb51.net/do/uploads/litimg/140314/0944332514F.jpg"> 节奏大师全P破解版</a><em class="xj star6"></em></li>
  5. <li><a href="https://m.jb51.net/game/207971.html"><img src="//files.jb51.net/do/uploads/litimg/140821/11594R51423.gif">海岛奇兵国服内购破解版</a><em class="xj star5"></em></li>
  6. <li><a href="https://m.jb51.net/game/144709.html"><img src="//files.jb51.net/do/uploads/litimg/140318/161504236013.gif">天天炫斗破解版</a><em class="xj star5"></em></li>
  7. <li><a href="https://m.jb51.net/game/80896.html"><img src="//files.jb51.net/do/uploads/litimg/130503/1J21Va46.jpg">完美女友完整版</a><em class="xj star5"></em></li>
  8. </ul>
  9. <p><ul id="thelist3"></ul>
  10. <script>
  11. alert($('#thelist2').children().length)
  12. alert($('#thelist3').children().length)
  13. $thelist3 = $('#thelist3');
  14. if($thelist3.children().length==0){
  15. //插入广告
  16. }
  17. /*
  18. thel3con = $('#thelist3').html();
  19. alert(thel3con.length);
  20. if(thel3con=""){
  21. alert("空");
  22. }else{
  23. alert("非空");
  24. }
  25. */
  26. </script>

方法二、

  1. String.prototype.isEmpty = function () {
  2. var s1 = this.replace(/[\r\n]/g, '').replace(/[ ]/g, ''),
  3. s2 = (s1 == '') ? true : false;
  4. return s2;
  5. };
  6. $list.html().isEmpty();

if( $("#list").html() === "" ){} 用三个等号更符合

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

vue地区选择组件使用步骤详解

vue mint-ui tabbar组件使用步骤详解

以上就是jquery判断元素内容是否存在的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行