将多个jQuery条件语句合并到一个查询中

Consolidate multiple jQuery conditional statements to a single query?

本文关键字:一个 查询 合并 jQuery 条件 语句      更新时间:2023-09-26

在我的网页上,我为页面上呈现的每条记录输出jQuery,如下所示:

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

注意,在元素ID上有服务器绑定,以确保每个记录都有jQuery处理。是否有一种方法可以通过嵌入条件语句在页面上只做一次,例如"对于所有$(this.ID + ' .attachmentsClick'),仅当$('.attachments.content').html()修剪为空白时隐藏"?

您可以使用jQuery的过滤器函数将潜在元素集减少到具有空内容的元素集,然后隐藏它们:

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

假设您将"attachmentsClick"类分配给所有行元素。它不需要行元素的ID。只要在你的内容加载后运行这个命令,它就会隐藏所有类为"attachmentsClick"的元素,并且类为"content"的子元素在裁剪时为空。

你的HTML可能看起来像:

<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>

您可以使用.each().someCommonClass应该在每个具有ID的服务器上。

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