开发者

Consolidate multiple jQuery conditional statements to a single query?

开发者 https://www.devze.com 2023-04-01 14:43 出处:网络
On my web page, I output jQuery for each record that is rendered on the page like this: if ($.trim($(\'#attachment<%# Eval(\"Id\")%> .content\').html()) == \'\') {

On my web page, I output jQuery for each record that is rendered on the page like this:

if ($.trim($('#attachment<%# Eval("Id")%> .content').html()) == '') {
  $('#attachmentClick<%# Eval("Id")%>').hide();
}

Notice there is server binding on the element ID to make sure each record has the jQuery processed. Is there a way to do this only once on the page by embedding the conditional开发者_开发技巧 statement, such as "for all $(this.ID + ' .attachmentsClick'), hide only if $('.attachments.content').html() trimmed is blank"?


You could use jQuery's filter function to reduce the set of potential elements to those with empty content, and then hide them:

$('.attachmentsClick').filter(function(){
    return $.trim($(this).find('.content').html()) == '';
}).hide();

This assumes that you give the class of "attachmentsClick" to all of your row elements. It does not need the ID of the row elements. Just run this after your content has loaded, and it will hide all elements with a class of "attachmentsClick" that have a child with a class of "content" which is empty when trimmed.

Your HTML might look something like:

<div class="attachmentsClick"><!-- this one will be hidden -->
  <div class="content"></div>
</div>

<div class="attachmentsClick"><!-- this one will be hidden too -->
  <div class="content">     </div>
</div>

<div class="attachmentsClick"><!-- this one will NOT be hidden -->
  <div class="content"><p>some content<p></div>
</div>


You can use .each(). .someCommonClass should be on each one that has the ID.

$('.someCommonClass').each(function(i, e) {
   var $e = $(e);
   if ($.trim($('.content', $e).html()) == '')
       $e.hide();
});
0

精彩评论

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