jQuery / HTML匹配div的文本

时间:2014-09-02 14:42:44

标签: javascript jquery html css regex

这是我的第一个问题。

如何使用正则表达式(或任何其他更好的方法)根据其中的文本匹配div A和​​div B(两者都有相同的文本),然后删除匹配的div B?

示例HTML ::

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

4 个答案:

答案 0 :(得分:1)

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

(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
        }
    });
}());

JSFiddle

答案 1 :(得分:0)

var divA = $(".A").text(); //gives you text inside i.e. Hello
var divB = new RegExp($(".B").text()); //gives you text inside i.e. Hello

//for matching 
if(divA.test(divB)) //returns true if matched 
  $(".B").remove();//for deleting div B

答案 2 :(得分:0)

尝试

$("div:not(.A):contains("+$(".A").text()+")").remove()

jsfiddle http://jsfiddle.net/guest271314/q5aok44c/

答案 3 :(得分:-1)

我已点击按钮点击。试试吧

<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();
        }
    });