jQuery在数据库值为NULL时隐藏HTML标记


jQuery to hide a HTML tag if the database value is NULL

我正在使用Dreamweaver内置的PHP功能来构建一个小型应用程序。我在一个重复的ul,li结构中检索数据,它看起来像这样。

  • 客户名称
  • 工作描述
  • 竣工年份

客户名称和工作描述将始终具有值,完成年份可能具有空值。如果完成年份为空,则不应显示"li"。

我正试图用jQuery来实现这一点,但对我来说看起来很复杂。我能用PHP实现吗?

$array = array('client_name'=>'John', 'job_descr'=>'Programming', 'year'=>null);
foreach ($array as $data) {
    echo '<ul>';
    ($data['client_name']!=null)?echo '<li>'.$data['client_name'].'</li>':echo '';
    ($data['job_descr']!=null)?echo '<li>'.$data['job_descr'].'</li>':echo '';
    ($data['year']!=null)?echo '<li>'.$data['year'].'</li>':echo '';
    echo '<ul>';
}

如果我理解正确,这就是你所需要的。

用PHP做这件事是合乎逻辑的——你必须向我们展示PHP源代码来帮助你——这只需要一个if语句来检查null,如果它是true,则不回显该列表。。但是为了回答你的jquery问题。。如果你的输出是这样的:

<ul id="this_is_the_list">
    <li>
        <ul>
            <li>Client name value</li>
            <li>Job desc value</li>
            <li>This isnt null</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>Another name value</li>
            <li>Another Job desc value - this one will be null</li>
            <li></li>
        </ul>
    </li>
</ul>​

你的jquery是:

$(document).ready(function() {
        //for each additional list within the target list
        //which has a 3rd li (i would suggest giving this a
        //class instead to better target it).
        $('#this_is_the_list li li:nth-child(3)').each(function() {
            if($(this).text().length < 1) { //if its empty
                 $(this).parents('#this_is_the_list > li').remove(); //remove its parent list item
            }
        });
    });​

在这里演示:http://jsfiddle.net/QxcLS/