如何检查文本是否与所需文本几乎相同

时间:2015-10-18 20:52:55

标签: javascript jquery html

我想检查我的textarea的值是否与要求几乎相同,例如:

我有一个HTML代码:

<textarea class="ab" placeholder="Type here"></textarea>
<div class="result">
</div>

和Jquery代码:

$(document).ready(function(){

  $(".btn").click(function(){
  var a = $(".ab").val();
  var b = $(".result").html();
    /* */



if(a.indexOf('Which of the following is generally true about Open Source software?') >= 0){$('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');}    /* */
    else{
      $(".result").html("error");

    }
  });

}); 

这段代码并不像我想要的那样工作,这正是我试图做的。但我想要的是例如当$('.ab')的值与Which of the following is generally true about Open Source software?the following is generally true等文本true about the Open Source几乎相同时,$(".result")仍然将html设为Its usually developed on a volunteer basis and anyone is free to change it (correct).

那么我该怎么做呢,谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

尝试将输入文本拆分为数组,使用$.each()迭代输入单词,如果输入单词与所选短语中的至少五个单词匹配,则返回true,否则在if返回false;例如。;尝试在textarea

输入或粘贴
  

the following is generally truetrue about the Open Source

&#13;
&#13;
$(document).ready(function() {

  $(".btn").click(function() {
    var a = $(".ab");
    var b = $(".result");
    var arr = a.val().split(/\s+/);
    var n = 0;
    var phrase = "Which of the following is generally true about Open Source software?";
    $.each(arr, function(key, val) {
      if(phrase.indexOf(val) >= 0) ++n;
    })
  
    if (n >= 5) {
     b.html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
    }
    else {
      b.html("error");
    };
    a.val(""); n = 0;
  });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<textarea class="ab" placeholder="Type here"></textarea>
<div class="result"></div>
<button class="btn">click</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

实际上它应该是:

    $(document).ready(function(){
        $(".btn").click(function(){
            var a = $(".ab").val();
            var b = $(".result").html();
            var c = 'Which of the following is generally true about Open Source software?';
            console.log(c.indexOf(a));
            if(c.indexOf(a) >= 0){
                $('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
            } else {
                $(".result").html("error");
            }
        });

    }); 

<textarea class="ab" placeholder="Type here">following is generally true about Open Source</textarea>
<div class="result"></div>
<button class="btn">test</button>