选择Jquery nth-child问题

时间:2015-07-23 09:23:59

标签: javascript jquery html

我必须按照表格

enter image description here

我有按钮'添加'这会为我的表创建一个新行

$(document).on('click','#add',function() {
    $('#table tr:last').after('<tr bgcolor="#FFFFFF">' +
        '<td> <select>' +
            '<option value="1">1</option>' +
            '<option value="2">2</option>' +
            '<option value="3">3</option>' +
            '<option value="4">4</option>' +
        '</select> </td>' +
        '<td style="display:none">A number</td>' +
        '<td>Test</td>' +
        '<td id="save">Save</td>' +
        '<td id="delete">Delete</td>' +
        '</tr>');
});

如您所见,我有一个下拉列表(1,2,3,4)和一个简单的隐藏文字。

当我点击“保存”时,我会保存下拉列表的值,隐藏下拉列表,显示“&#39; A”数字&#39;字段并将其替换为下拉列表的值。

我也改变了&#39; Save&#39;到&#39;编辑&#39;

    $(document).on('click','#save',function() {
        this.id = "edit";
        this.innerHTML = "Edit";
        var qte = $(this).parent().find("td:first :selected").text();
        $(this).parent().find("td:first").hide();
        $(this).parent().find(":nth-child(2)").text(qte);
        $(this).parent().find(":nth-child(2)").show();
    });

当我想要编辑&#39;再次,我想用下拉列表替换数量文本。所以我隐藏文字并重新显示<select>标记

$(document).on('click','#edit',function() {
    this.id = "save";
    this.innerHTML = "Save";
    $(this).parent().find("td:first").show();
    $(this).parent().find(":nth-child(2)").hide();
});

一切正常,但最后一行会删除<option value="2">2</option>

<select>

我完成了这个

enter image description here

我不知道如何解决这个问题。这可能不是最好的解决方案,我愿意接受任何其他方式来实现这一目标。

2 个答案:

答案 0 :(得分:1)

:nth-child(2)将获取该父母内所有内容的第二个孩子。您可能希望将其更改为td:nth-child(2)

顺便说一句,我也会将td:first更改为td:first-child,因为这是自然的CSS选择器,建议更快:

https://api.jquery.com/first-selector/

  

因为:首先是jQuery扩展而不是CSS规范的一部分,使用的查询:首先不能利用本机DOM querySelectorAll()方法提供的性能提升。要在使用时获得最佳性能:首先选择元素,首先使用纯CSS选择器选择元素,然后使用.filter(“:first”)。

答案 1 :(得分:0)

此行创建问题: -

$(this).parent().find(":nth-child(2)").hide();

因为它会隐藏第二个位置的所有内容,这就是隐藏所需标签的原因。

更好地提及你想要隐藏的内容..

在你的情况下,它是td,

$(this).parent().find("td:nth-child(2)").show();