【问题标题】:Jquery remove closest tr failjQuery删除最近的tr失败
【发布时间】:2011-02-04 15:03:28
【问题描述】:

当 html 中存在某些措辞时,我想进行操作以删除最近的表格。

我不能假设 span 类会存在那里,因为 html 是从另一端检索的,他们可以随时通过添加、删除任何类来更改它。

需要在页面加载时完成,而不是在点击里面的class/id事件时。

有点挑战性。知道如何实现这一目标吗?

在页面加载时,

jquery 检测页面中是否存在“Hello how are you”。

If exist
    remove the whole td or tr or table for this particular.
else
    do nothing.
end

代码如下:

function replaceText() 
{

    var debug;
    debug= "";


    $("*").each(function() { 
        if($(this).children().length==0) 
    { 
//            $(this).text($(this).text().replace('Hello how are you', 'yohoo')); 

        debug= debug + $(this).val() + "<br>";

        if($(this).val()=="Hello how are you")
        {
            $(this).closest('table').remove();
        }

        } 
    });

//alert(debug);

}


<div>


<table>

    <tr>

    <td colspan="2">


        <div>


            <table>

            <tr>

            <td ><span class="myclass">Hello how are you</span></td>

            <td><a href="testing.php"></a></td>

            </tr>

            </table>


        </div>


    </td>

    </tr>


    <tr colspan="2">
        <table>

        <tr>

        <td><b>want to remove this</b></td>

        </tr>

        </table>
    </tr>

    <tr>
        <td>other content 1</td>
        <td>other content 2</td>
    </tr>

</table>

</div>

【问题讨论】:

  • 我认为你想要.text() 而不是.val()。 val 用于输入、选择、文本区域...

标签: jquery traversal dom-manipulation


【解决方案1】:

您可以使用:contains 来检查文本是否存在:

$(":contains('Hello how are you')").each(function(n){
    if ($(this).children().length == 0){
        $(this).closest('table').remove();
    }
});

此代码将遍历包含文本“你好,你好吗”的所有元素。如果您想要完全匹配,您还可以查看$(this).text() == 'Hello how are you'。一旦找到这些元素,它就会检查它们是否没有任何子元素,然后如果它们满足该条件,则删除最近的表。

要在页面加载时运行此代码,请将其包装在 document.ready 函数中:

$(document).ready(function(){
  ...
});

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 2012-08-14
    • 1970-01-01
    • 2014-02-20
    • 2017-03-20
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多