开发者

jquery javascript strange behavior in .html()

开发者 https://www.devze.com 2023-01-26 07:20 出处:网络
I have the next simple html: <td id=\"comment_td\"></td>. There are two spaces in td. I check the td html like this:

I have the next simple html: <td id="comment_td"> </td>. There are two spaces in td. I check the td html like this:

if (!$('#comment_td').html()) 开发者_StackOverflow社区{
    $('#comment_td').html('No Comments');
}

But it works only in IE))) In Firefox this condition is not perform. Can you help me?


If you are trying to see if the is empty of all content, you may want to trim any spaces from it.

if($('#comment_td').html().trim().length == 0) {
    $('#comment_td').html('No Comments');
}

Some browsers remove duplicate spaces, and may even remove all spaces between two tags if there is no other content.

If you wish to check if there are spaces, you should really output the spaces using the &nbsp; character, like this:

<td id="comment_td">&nbsp;&nbsp;</td>


Try the following:

var Comment = $('#comment_td');
if(Comment.html().trim().length == 0)
{
    Comment.html('No Comments');
}

By checking the trimmed length your specifically stating to remove white space, as some browsers like IE will remove white space where as others will not, so in firefox because theres a space in the element its actually exists.

If your comments within the comments_td are in containers then you can also check the children, for example:

<td id="comment_td">
   <p class="comment">A comment</p>
   <p class="comment">A comment</p>
</td>

Then within jQuery you can do:

if($("#comments_td > p.comment").size() == 0)
{
   //No Comments.
}


if ($('#comment_td').html().trim() == "") {
    $('#comment_td').html('No Comments');
}


var empty = $.trim( $('#comment_td').html() ).length == 0;

if ( empty ) {
  // do whatever
}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

And

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

render both of above differently under firefox.

This might be related to your !DOCTYPE defined on the very first line of your HTML document, before HTML tag. Read more about these Mysterious Gaps.

0

精彩评论

暂无评论...
验证码 换一张
取 消