Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery/HTML匹配div的文本_Javascript_Jquery_Html_Css_Regex - Fatal编程技术网

Javascript jQuery/HTML匹配div的文本

Javascript jQuery/HTML匹配div的文本,javascript,jquery,html,css,regex,Javascript,Jquery,Html,Css,Regex,这是我的第一个问题 如何使用正则表达式或任何其他更好的方法来匹配div A和div B,这两个div都基于它们内部的文本具有相同的文本,然后删除匹配的div B 示例HTML:: <div class="A"> Hello </div> <div class="B"> Hello </div> <div class="C"> Bye </div> ......... and so on. 我已经在按钮点击上写了。试试看 &

这是我的第一个问题

如何使用正则表达式或任何其他更好的方法来匹配div A和div B,这两个div都基于它们内部的文本具有相同的文本,然后删除匹配的div B

示例HTML::

<div class="A"> Hello </div>
<div class="B"> Hello </div>
<div class="C"> Bye </div>
......... and so on.

我已经在按钮点击上写了。试试看

<div class="A">Hello </div>
<div class="B">Hello </div>
<div class="C">Bye </div>
<input type="button" value="click" id="btn" />

 $('#btn').click(function () {
        if ($('.A').text() == $('.B').text())
        {
            $(".A").remove();
        }
    });

有很多方法可以做到这一点,一种方法是进行查找

(function (){
    var lookup = {};  //store text here
    $("div").each( function () {  //loop through the elements
        var elem = $(this);  //reference to current
        var txt = $.trim(elem.text());  //get its text
        if (lookup[txt]) {  //if we have had this text already, remove the element
           elem.remove();
        } else {
            lookup[txt] = true;  //set the key in the lookup
        }
    });
}());
试一试


jshiddle

这里更大的问题是什么?您是否正在尝试删除具有相同内容的连续div?Shikhars使用正则表达式解析html是个坏主意,您应该使用html解析器,而不是使用html解析器。div可以是页面上混乱的任何地方。我只想根据文本将第一种div与页面上的另一种div进行匹配,然后删除第二种类型的div。@Fede-好的,那么?我只是想澄清一下。试试我的代码。它正按照你想要的方式工作
(function (){
    var lookup = {};  //store text here
    $("div").each( function () {  //loop through the elements
        var elem = $(this);  //reference to current
        var txt = $.trim(elem.text());  //get its text
        if (lookup[txt]) {  //if we have had this text already, remove the element
           elem.remove();
        } else {
            lookup[txt] = true;  //set the key in the lookup
        }
    });
}());
$("div:not(.A):contains("+$(".A").text()+")").remove()