jquery判断元素内容是否为空的方法 原创

夕阳的金辉把绿色的林海染成金黄一片。火红的太阳慢慢地西落了,归鸟们纷纷从我头上飞过,飞回到它们的小巢。一轮明月从东方静悄悄地升上来。夜空中美丽的星星,似乎在眨着眼睛对我说:夜,来了!

用jquery获取元素内容需要分两个情况:

input 用val();

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

是否为空的判断方法:

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

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

jQuery验证文本框内容不为空

通过$.fn 扩展jQuery方法

/**
 * 校验文本是否为空
 * tips:提示信息
 * 使用方法:$("#id").validate("提示文本");
 * @itmyhome
 */
$.fn.validate = function(tips){

  if($(this).val() == "" || $.trim($(this).val()).length == 0){
    alert(tips + "不能为空!");
    throw SyntaxError(); //如果验证不通过,则不执行后面
  }
}

html元素用html();

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

是否为空的判断方法:

if(value.length == 0){

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

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

方法一

<script type="text/javascript" src="http://m.haodaima.com/skin/mobile/js/jquery.min.js"></script>
<div><ul id="thelist2">
<li><a rel="nofollow noopener noreferrer" href="https://m.haodaima.com/game/140209.html"><img src="//files.haodaima.com/do/uploads/litimg/140228/100331632c.jpg">天天飞车航哥破解版</a><em class="xj star5"></em></li>
<li><a rel="nofollow noopener noreferrer" href="https://m.haodaima.com/game/143515.html"><img src="//files.haodaima.com/do/uploads/litimg/140314/0944332514F.jpg"> 节奏大师全P破解版</a><em class="xj star6"></em></li>
<li><a rel="nofollow noopener noreferrer" href="https://m.haodaima.com/game/207971.html"><img src="//files.haodaima.com/do/uploads/litimg/140821/11594R51423.gif">海岛奇兵国服内购破解版</a><em class="xj star5"></em></li>
<li><a rel="nofollow noopener noreferrer" href="https://m.haodaima.com/game/144709.html"><img src="//files.haodaima.com/do/uploads/litimg/140318/161504236013.gif">天天炫斗破解版</a><em class="xj star5"></em></li>
<li><a rel="nofollow noopener noreferrer" href="https://m.haodaima.com/game/80896.html"><img src="//files.haodaima.com/do/uploads/litimg/130503/1J21Va46.jpg">完美女友完整版</a><em class="xj star5"></em></li>
</ul>
<div><ul id="thelist3"></ul>
<script>
alert($('#thelist2').children().length)
alert($('#thelist3').children().length)
$thelist3 = $('#thelist3');
if($thelist3.children().length==0){
//插入广告
}
/*
thel3con = $('#thelist3').html();
alert(thel3con.length);
if(thel3con=""){
alert("空");

}else{
alert("非空");
}
*/
</script>

方法二、

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

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

本文jquery判断元素内容是否为空的方法 原创到此结束。笑着活是一辈子,哭着活也是一辈子。反正只要活着就笑着活下去吧。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
JS获取鼠标点击时的位置

vue、nginx部署后刷新报404错误的解决方法

electron-builder配置项

VUE聊天页面自动滚动到底部

VUE CTRL+ENTER换行,ENTER发送消息