比较两个div之间的jquery中的单词并更改匹配单词的颜色

时间:2018-01-30 04:52:25

标签: javascript php jquery html5

我有两个div包含句子

DIV1:

 i have a pen in my pocket which is very costly.

DIV2

i have a  costly watch.

形成上面给出的div我想比较句子找到并突出显示两个div中存在的相同单词

4 个答案:

答案 0 :(得分:1)

这是一个小代码,可以帮助您启动并获取两个div /行之间的常用词:

$(document).ready(function() {
  var text1 = $('#div1').text();
  var text2 = $('#div2').text();

  var text1Words = text1.split(' ');
  var text2Words = text2.split(' ');

  var commonWords = $(text1Words).filter(text2Words).toArray();
  console.log(commonWords);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div1'>i have a pen in my pocket which is very costly.</div>

<div id='div2'>i have a costly watch.</div>

答案 1 :(得分:1)

HTML

<div id="div1">
   i have a pen in my pocket which is very costly
</div>

<div id="div2">
   i have a costly watch
</div> 

<强> Jquery的

$(document).ready(function(){
var text1 = $('#div1').text().trim();
var text2 = $('#div2').text().trim();

var text1_arr = text1.split(' ');
var text1_temp = text1.split(' ');
var text2_arr = text2.split(' ');  

text1_arr.map(function(ele, index){
  if($.inArray( ele, text2_arr)!=-1){
    text1_arr[index] = '<b>'+ele+'</b>';
  }
});
text2_arr.map(function(ele, index){
  if($.inArray( ele, text1_temp)!=-1){
    text2_arr[index] = '<b>'+ele+'</b>';
  }
});

 $('#div1').html(text1_arr.join(' '));
 $('#div2').html(text2_arr.join(' '));
})

答案 2 :(得分:0)

您可以尝试这样

<div id="div1">
    i have a pen in my pocket which is very costly
</div>

<div id="div2">
     i have a  costly watch
</div>

<div id= "final">
</div>
在jquery中

$(document).ready(function() {
 var div1 = $.trim($("#div1").text());
// alert(div1);
var divArray = div1.split(' ');
//alert(divArray);
var div2 = $.trim($("#div2").text());
var div2Array = div2.split(' ');

var html = '';
for(i = 0; i< div2Array.length; i++){
//alert(divArray[i]); //outputs individual numbers in array

var index = $.inArray( div2Array[i], divArray);

console.log(div2Array[i]);
if( index != -1 ) {
    html += "<b>"+div2Array[i]+"</b> ";
} else {
 html += div2Array[i] + " ";
}
}

console.log(html);
$("#final").html(html);
});

小提琴示例

https://jsfiddle.net/o2gxgz9r/21465/

答案 3 :(得分:0)

尝试以下方式:

&#13;
&#13;
var one = $('#one').text().split(' ');
var two = $('#two').text().split(' ');
one.forEach(function(w, i){
  var ind2 = two.indexOf(w);
  if(two.includes(one[i])){
    one[i] = "<span style='color:red'>"+w+"</span>";
    two[ind2] = "<span style='color:red'>"+w+"</span>";
  }
})

$('#one').html(one.join(' '));
$('#two').html(two.join(' '));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one">i have a pen in my pocket which is very costly</div>
<div id="two">i have a costly watch</div>
&#13;
&#13;
&#13;