检查div是否为空问题

时间:2012-11-28 15:14:12

标签: jquery

我想检查div是否为空,如果是这样我想向它添加文本'empty'。

我做错了什么?谢谢!

js Fiddle File

HTML

<div class="staff-row">
    <img alt="" src="foo.jpg" />
    <h2>Lorem Ipsum! FOOO!</h2>
    <p>Lorem Ipsum</p>
  </div>
  <!-- eo : staff-row --> 

的jQuery

$('.staff-row').mouseenter(function() {
    if ($('.staff-row').is(':empty')) {
        $('.staff-row').text('empty');
    } else {
        $('.staff-row').text('full');
    }
});​

1 个答案:

答案 0 :(得分:4)

您需要使用$(this)代替$('.staff-row'),同时make sure there is not space between div opening and closing tag.

<强> Live Demo

$('.staff-row').mouseenter(function() {
    if ($(this).is(':empty')) {
        $(this).text('empty');
    } else {
        $(this).text('full');
    }
});​

如果您想在div标签之间留出空格,可以使用if($.trim($(this).text()).length == 0)

<强> Live Demo

$('.staff-row').mouseenter(function() {
    if($.trim($(this).text()).length == 0){
        $(this).text('empty');
    } else {
        $(this).text('full');
    }
});​
相关问题