短语与jQuery的比较

时间:2011-10-15 15:20:45

标签: javascript jquery

我想将它们(标记<p>)一起比较,如果它们相似则删除它们,并显示其他不相似的单词。但是这段代码被删除how are you?因为它类似于how,我该怎么办?

示例: http://jsfiddle.net/CCMKu/

<span style="display: none;">
    <p>hello</p>
    <p>hi</p>
    <p>how</p>
    <p>what</p>
</span>

<div class="remove">
    <p>hello</p>    
    <p>how</p>    
    <p>how are you?</p>
    <p>what</p>
    <p>fine</p>
    <p>hi</p>
</div>



$("span p").each(function () {
    $(".remove p:contains(" + $(this).text() + ")").remove();
});

输出为fine,以防输出应为fine $ how are you?

2 个答案:

答案 0 :(得分:1)

为您更新了小提琴:http://jsfiddle.net/CCMKu/3/

var input = [];

/*
 * Storing all values
 * in a single array for
 * a faster access
 */
$("span p").each(function () {
    input.push($(this).text());
});

$(".remove p").each(function () {
    var $this = $(this);

    /*
     * Now use the inArray utility
     * function to find duplicates
     *
     * EDIT: Added toLowerCase() to allow
     * case-insensitive matching
     */
    if ($.inArray($this.text().toLowerCase(), input.toLowerCase()) !== -1) {
        $this.remove();
    }
});

答案 1 :(得分:1)

尝试:

$("span p").each(function () {
    var item=$(this).text();
    $(".remove p").filter(function(){return $(this).text()==item}).remove();
});