通过查找带子句的内容来删除表行

时间:2014-03-21 23:37:45

标签: javascript

我有这段代码:

<table>
    <tbody>
        <tr><td>Table 1</td></tr>
    </tbody>
</table>

<table>
    <tbody>
        <tr>
            <td align="left">Number</td>
            <td><b>33</b></td>     
        </tr>
        <tr>        
            <td width="150" align="left">Field</td>
            <td>XXXX</td>
        </tr>
        <tr>    
            <td align="left">Select: </td>
            <td colspan="4">
                <select name="status" size="1">
                    <option selected="selected" value="2">one</option>
                    <option value="1">two</option>
                </select>                   
            </td>
        </tr>
    </tbody>
</table>

我希望通过使用纯Javascript搜索“Field”来删除此行:

    <tr>
        <td width="150" align="left">Field</td>
        <td>XXXX</td>
    </tr>

当我的第二张表中有一行33,66或99时:

    <tr>
        <td align="left">Number</td>
        <td>33</td>     
    </tr>

问题是我没有任何身份证或类别可供识别!我想使用Greasemonkey代码。


在这里,您可以看到我桌子的 JSFIDDLE 在这里,您可以看到 JSFIDDLE 它的外观。

最好的问候bernte

1 个答案:

答案 0 :(得分:1)

你走了:

var disallowedValues = ['33', '66', '99'];    
var cols = document.getElementsByTagName('td');
var colslen = cols.length;
var i = -1;
var disallowedTable;

while(++i < colslen){
    // look for the td where the disallowed values are
    if(disallowedValues.indexOf(cols[i].innerHTML) >= 0)
    {
        // get the table where the disallowed values is
        disallowedTable = cols[i].parentNode.parentNode.parentNode;
        // break the cicle to stop looking for other rows
        //break;
    }
}

// look for the 'Field' value only on the table that has the disallowed value
var cols = disallowedTable.getElementsByTagName('td');
cols = disallowedTable.getElementsByTagName('td');
colslen = cols.length;
i = -1;

while(++i < colslen){
    // look for the td where the 'Field' value is
    if(cols[i].innerHTML == 'Field')
    {
       // get the tr for such td
        var deletionTR = cols[i].parentNode;       
        //delete that tr
        deletionTR.parentNode.removeChild(deletionTR);
        // break the cicle to stop looking for other rows
        break;
    }
}

如果jquery是一个选项,你总是可以做一个更简单的版本。