使用jQuery或Angular动态添加或删除表行

Dynamically add or remove table rows with jQuery or Angular?

本文关键字:删除 添加 动态 jQuery Angular 使用      更新时间:2023-09-26

这是我的代码。我使用Symfony/Twig来传递变量和翻译字符串(如果有人不确定{{}}{% trans %}等的用途)。

请看我有glyphicon glyphicon-camera的那一行——我想要的是用户能够点击它,并且在它的正下方出现一个新行,其中包含row.getPhoto()的内容——只有当row.getPhoto()不为空时,图标才会出现,因此点击它总是意味着有内容要显示。

同样,再次单击照片图标将使该行消失。

我该怎么做?我不确定我应该使用jQuery还是Angular(我在项目的其他地方都使用这两种方法,所以这两种都很容易使用)。欢迎任何意见,谢谢。

    <table class="table">
    <tr>
        <th width="10%">{% trans %} header.item {% endtrans %}</th>
        <th width="60%">{% trans %} header.action {% endtrans %}</th>
        <th width="10%">{% trans %} header.option1 {% endtrans %}</th>
        <th width="10%">{% trans %} header.option2 {% endtrans %}</th>
        <th width="10%">{% trans %} header.option3 {% endtrans %}</th>
    </tr>
    {% for row in showRows(allItems) %}
        <tr>
            <td>
                {{ row.getItem() }}
            </td>
            <td>
                {{ row.getAction() }} {% if row.getPhoto() is not null %} <span class="pull-right show-hide-photo glyphicon glyphicon-camera"></span>{% endif %}
            </td>
            <td>
                {% if row.getOption1() %}<span class="glyphicon glyphicon-ok"></span>{% endif %}
            </td>
            <td>
                {% if row.getOption2() %}<span class="glyphicon glyphicon-ok"></span>{% endif %}
            </td>
            <td>
                {% if row.getOption3() %}<span class="glyphicon glyphicon-ok"></span>{% endif %}
            </td>
        </tr>
    {% endfor %}
    </table>

我现在唯一的jQuery是这样的,当悬停在上面时,使图标看起来像一个链接:

    // Photo button
    $('.show-hide-photo').css('cursor', 'pointer');

您总是可以在javascript代码上传递symphony2变量,因此您可以使用以下内容生成scirpt:

<scirpt>
$(.glyphicon).click(function(){
     $(.Some-other-class).toggle()
});
</script>

您可以将其他一些类的div元素或td元素隐藏起来,并在其中包含变量(就像您在静态html代码中所做的那样)。

您不需要js中的css指针,在css类中使用它可以在页面加载时使用,而不是在用户单击时使用。

对于你的点击,你可以做这样的事情,如果你的照片是一个链接,那么:

每当你想放置图像时,首先在你的树枝上使用<img src="{{row.photo}}" alt="" style="display:none;"/>

然后在你的js中点击照片按钮

$('.show-hide-photo').on('click', function(){
   $(this).closest('tr').find('img').toggle();
});

$(this)是您的显示隐藏照片按钮,closest('tr')将查找包含您的按钮的标签,然后find('img')将在该(行)内找到标签。在这种情况下,您不需要麻烦ID来选择右侧行等。