2017-04-15 44 views
0

我让用户在input中键入单词或句子,这将与其他字符串进行比较。然后,我在每个字符串结果运行.each,看是否有匹配的字符串,如果这样继续其他明智删除一些元素:比较字符串会给出错误的结果

var text2; 
 
var text2B; 
 
text2 = jQuery('#usp-title').val(); 
 
text2B = text2.toLowerCase(); 
 
jQuery("#datafetch").html(data).promise().done(function() { 
 
    jQuery("#datafetch ul li h2 a").each(function() { 
 
    var $this = jQuery(this); 
 
    if ($this.text().toLowerCase().trim() !== text2B.trim()) { 
 
     $this.parent().parent().remove(); 
 
     jQuery(".jumbotron").remove(); 
 
     jQuery("#componi").removeAttr("disabled", "disabled").show(); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="#usp-title" type="text">

jQuery(".jumbotron").remove();无论如何都会发生。我知道它,因为所有的结果都被$this.parent().parent().remove();删除了,我没有看到它们,只留下正确的匹配字符串结果。

data variable给人的项目清单:

<div id="#datafetch"> 
    <ul> 
    <li> 
     <h2> 
     <a>Lorem</a> 
     </h2> 
    </li> 
    <li> 
     <h2> 
     <a>Ipsum</a> 
     </h2> 
    </li> 
    <li> 
     <h2> 
     <a>Dolor</a> 
     </h2> 
    </li> 
    </ul> 

我甚至尝试:

if ($thisText !== text2B.trim()) { 
     jQuery(".jumbotron").hide(); 
     $this.parent().parent().remove(); 
     jQuery("#componi").removeAttr("disabled", "disabled").show(); 
     } else { 
     jQuery(".jumbotron").show(); 
    } 
+0

'data'变量中有什么? – ischenkodv

+0

在您的代码中.jumbotron在至少有一个字符串不匹配时被删除,因此它当然会在您的示例中被删除。 – endrju

+0

是的,但即使有匹配并且show()被调用,然后下一个比较将调用hide()(除非最后比较的字符串是正确的)。 – endrju

回答

1

有这码登录漏洞。 Jumbotron总是被删除,因为单个不匹配(在任何字符串上)将其删除。

在更新后的代码中(使用hide()和show())也存在类似的问题。即使匹配发生并且显示了超大号,然后下一次比较再次隐藏起来。

解决的办法是首先(在每个()循环之前)隐藏jumbotron并仅在匹配发生时显示它。