2017-02-13 61 views
1

我正在Ionic构建一个应用程序,我需要隐藏一些有空白区域的元素,并且里面有一些空白区域。我可以使用jQuery执行此操作,如下所示。隐藏元素如果为空或内部有空白(Ionic 2)

jQuery('.course p').filter(function() { 

     return $.trim($(this).text()) === '' 

    }).remove(); 

我有一个custom.js文件导入,但似乎没有发生什么? 有没有更好的方法来做到这一点?如果是这样,请给我一些建议。

谢谢!

+0

莫比NG-IF?....... – madalinivascu

+0

如果你想使用'.hide()',而不是'.remove()' – ramabarca

回答

0

我在片段中添加了三个p元素 - 一个带有空格,一个带有非打破空格,另一个带有文本。然后函数迭代每一个 - 确定是修剪后的内容,以摆脱空白,tehn add删除它。所以剩下的只是带有内容的单个p元素 - 注意我已经在p'元素周围放置了一个边框来显示它们。

我刚刚放了一个按钮,使初始状态可以看作是三个p元素,然后点击按钮 - 两个被删除。

第一个p是essentailly与边框折叠div - 所以它最初显示为粗线,第二个p是nbsp并显示为空框 - 然后最后一个是带文本的。这是点击按钮后将会保留的唯一一个。

$(document).ready(function(){ 
 
    $('#trimButton').click(function(){ 
 
     $('.course p').each(function(){ 
 
     if($(this).text().trim() === ''){ 
 
      $(this).remove();} 
 
     }) 
 
    }) 
 
    })
.course p{border:solid 1px red; margin-bottom:10px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="course"> 
 
    <p> </p> 
 
    <p>&nbsp;</p> 
 
    <p> test</p> 
 
</div> 
 
<hr/> 
 
<button type="button" id="trimButton">click me to remove the empty p elements</button>

0

从我的支票,你的代码应该做工精细;

$('#trim').click(function(){ 
 
\t jQuery('.course p').filter(function() { 
 
\t 
 
\t return $.trim($(this).text()) === '' 
 
\t 
 
\t }).remove(); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="course" > 
 
<p style="border:solid 1px red; margin-bottom:10px"> </p> 
 
<p style="border:solid 1px red; margin-bottom:10px">&nbsp;</p> 
 
<p style="border:solid 1px red; margin-bottom:10px">this is </p> 
 
<p style="border:solid 1px red; margin-bottom:10px"> this</p> 
 
</div> 
 
<button type="button" id="trim">Clear Empty Elements</button>

可以与js文件导入的方式或者也许是jQuery选择找不到元素的问题,因为它被命名错误?

或者,因为你正在使用angularjs,你应该考虑使用ng-if

ng-if="*yourDataSource*.name.indexOf(' ') !== -1" 

或ES2015

ng-if="*yourDataSource*.includes(' ')" 
+0

“*'$ .trim($(this).text())==='''不会返回true或false * - 是的,[是的它](https://jsfiddle.net/o6q1d0o2/)。 –

+0

其实你是非常正确的''.trim($(this).text())==='''确实会返回正确的值。这意味着你的代码应该工作。我已经在https://jsfiddle.net/vzjm7zz5/中试过了,它确实有效。也许是类命名问题或脚本文件如何导入。将编辑我的答案。 –