使用javascript或jquery比较2 div元素中的文本

Om3*_*3ga 38 html javascript jquery

我有以下2个div标签

<div class="one">
    +
   +++
    +
</div>
Run Code Online (Sandbox Code Playgroud)

第二个div标签

<div class="two">
    + +   ++++  + ++  + + +
    + ++ +++ + +++ ++ + +++
    + ++ + + ++ + + + + ++ 
</div>
Run Code Online (Sandbox Code Playgroud)

现在我想要找到的是否.one存在.two.如果是的话我们怎样才能在javascript中做到这一点?

更新

我想检查+模式.我的意思是

+ +++ +

存在于.two?模式必须在同一顺序中.two.

@shub答案似乎不起作用.这是答案的JSFiddle.

Clo*_*omp 19

第1部分:

要查看数据的匹配方式,您可能需要尝试将其转换为字母而不是字母.

<div class="one">
    g
   tuv
    J
</div>

<div class="two">
    a b   cdef  g hi  j k l
    m no pqr s tuv wx y zAB
    C DE F G HI J K L M NO 
</div>
Run Code Online (Sandbox Code Playgroud)

你必须做这样的事情:

从以下:one.innerText = g \n tuv \n J

它需要变成一个正则表达式,如:/ g | tuv | J/g

要查看交叉匹配,请将第二类的内容复制并粘贴到此站点中并删除"a","m"和"C"之前的间距:http://regexr.com/3eumc

第2部分

问题是如果"tuv"在字符串2中移动,它将不会被"g"锁定在"J"之上的"u"之上.

为了将"g"固定在"J"问题之上的"u"之上,我们必须将其视为游戏板的二维数据集.这意味着将字符串转换为矩阵(数组数组),其中每个字母加上每个空格都会被放入数组槽中.像这样:

var matrix = [
  // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 = columns. Remember to add +10, +20!
    [a| |b| | | |c|d|e|f| | |g| |h|i| | |j| |k| |l], // row 0
    [m| |n|o| |p|q|r| |s| |t|u|v| |w|x| |y| |z|A|B], // row 1
    [C| |D|E| |F| |G| |H|I| |J| |K| |L| |M| |N|O]    // row 2
];
Run Code Online (Sandbox Code Playgroud)

现在您可以查看是否:

if ((matrix[0][13] === 'g') 
    && (matrix[1][12] === 't') && (matrix[1][13] === 'u') && (matrix[1][14] === 'v') 
    && (matrix[2][13] === 'J')) {
    /* SUCCESS when all 5 letters appear & "g" is above "u" & "u" is above "J".
    The entire cross can move left or right, but lines 1, 2 & 3 can't shift 
    independently of the other 3 lines. Otherwise it should fail.
    */
} else {
    // FAIL
}
Run Code Online (Sandbox Code Playgroud)

第3部分......

我已经解决了这个矩阵搜索难题.请访问https://jsfiddle.net/briankueck/pern32vv/查看我的jsFiddle

以下是代码外观的核心.打开jsFiddle链接上的调试开关,看看它是如何运行的.:)

function getMatrix(cssSelector, canTrim) {
    // Built by, Clomp! @briankueck http://www.clomp.com
    var obj = $(cssSelector);
    if (obj) {
        var matrix = obj.text()

        /* Makes sure that we are selecting 3 lines, not 5 
         * as the example has a \n after <div ...>\n and before \n</div>
         */
        if (canTrim) {
            matrix = matrix.trim();
        }

        // Now split those 3 lines.
        matrix = matrix.split(/\n/);

        /* Trims each array in the matrix. Note: matrix[row] is a string, 
         * but we can treat a string as an array of characters.
         */
        if (canTrim) {
            // Trims each row, if desired.
            for (var row = 0; row < matrix.length; row++) {
                matrix[row] = matrix[row].trim();
            }
        } else {
            // Gets rid of spaces before matrix 1 in this demo.
            var maxLength = 0;
            var space = ' '; // You can also use a period here to see how it works.
            var tempMatrix = [];
            for (var row = 0; row < matrix.length; row++) {
                // This cuts the rows down (vertically) from 5 to 3.
                if (matrix[row].trim().length > 0) {
                    matrix[row] = matrix[row].replace(/\s/g, space);
                    matrix[row] = matrix[row].replace(/\t/g, space);
                    tempMatrix.push(matrix[row]);

                    if (matrix[row].length > maxLength) {
                        maxLength = matrix[row].length;
                    }
                }
            }

            /* This loops those 3 rows (horizontally) & slices the 1st character off 
             * each array if they are all identical & only contain spaces, which we are 
             * tracking with the period character '.' as dots.
             */
            var charactersToStrip = 0;
            for (var column = 0; column <= maxLength; column++) {
                for (var row = 0; row < tempMatrix.length; row++) {
                    if (tempMatrix[row][column] !== space) {
                        break;
                    } else if (row === (tempMatrix.length - 1)) {
                        charactersToStrip++;
                    }
                }
            }

            /* Strips characters, without removing the space before "g" 
             * and the space before "J".
             */
            for (var column = 0; column < charactersToStrip; column++) {
                for (var row = 0; row < tempMatrix.length; row++) {
                    tempMatrix[row] = tempMatrix[row].substring(1);
                }
            }
            matrix = tempMatrix;
        }
    }

    return matrix;
}

function matrixSearch(matrixOne, matrixTwo) {
    // Built by, Clomp! @briankueck http://www.clomp.com
    var space = ' '; // You can also use a period here to see how it works.

    // This is for " g". First we trim it, as we only want the "g" character.
    var searchChar = matrixOne[0].trim();

    // Next we find the lock position.
    var firstCharPosition = matrixTwo[0].indexOf(searchChar);

    var matchingRows = -1;
    if (firstCharPosition > -1) {

        // This should be 1 & not 0.
        var matchingCharInMatrixOne = matrixOne[0].indexOf(searchChar);

        // Now we can find the starting index of character 0 in each row of matrixTwo:
        var startIndex = firstCharPosition - matchingCharInMatrixOne;

        // This simultaneously scans rows 1, 2 & 3 in both matricies.
        var matchingRows = 0;
        for (var row = 0; row < matrixOne.length; row++) {
            /* We now know both the startIndex = 11 & the lock position = 12. 
             * So let's use them for "tuv" and " J".
             */
            var endIndex = startIndex + matrixOne[row].length;
            var i = -1;
            for (var column = startIndex; column < endIndex; column++) {
                i++;
                if (matrixOne[row][i] !== space) {
                    var matrixOneCharacter = matrixOne[row][i];
                    var matrixTwoCharacter = matrixTwo[row][column];
                    if (matrixOneCharacter !== matrixTwoCharacter) {
                        break;
                    } else if (column === (endIndex - 1)) {
                        // Found it!
                        matchingRows++;
                    }
                }
            }
        }
    }

    // Now we can find it:
    var isFoundInMatrixTwo = ((matchingRows > -1) 
        && (matchingRows === matrixTwo.length)) ? true : false;

    return isFoundInMatrixTwo;
}

var cssSelector1 = '.one';
var cssSelector2 = '.two';

var matrixOne = getMatrix(cssSelector1, false);
var matrixTwo = getMatrix(cssSelector2, true);

var isFound = matrixSearch(matrixOne, matrixTwo);
console.log('Is matrix 1 in matrix 2? ', isFound);
Run Code Online (Sandbox Code Playgroud)

请享用!

顺便说一下,来自Clomp的圣诞快乐Stack Overflow社区!


sin*_*ake 8

好吧,我们这里已经有了很好的答案,但是......这里有一个方法.:)

基本上:过滤输入,得到干净的模式/矩阵(假设在开始时会有两个空格 - 必须解决这个问题!),针对另一个模式进行测试(实际上 - 从两者中制作HTML结构和数组=>比较它们)

也可以用视觉表示正在发生的事情.

代码是暴行,可以而且应该被清理(但它有点工作,哈哈):

spacer='-';

pattern=$('.one').text().replace(/ /g,spacer).split('\n');

patt=pattern.filter(function(val){
   if(val.indexOf('+')>=1) {
   
   
 return val;
   }
});
patt = patt.map(function(x){
   return x.slice(2);
});


var lgth = 0;
var longest;

for(var i=0; i < patt.length; i++){ // http://stackoverflow.com/questions/6521245/finding-longest-string-in-array 
    if(patt[i].length > lgth){
        var lgth = patt[i].length;
        longest = patt[i];
    }      
} 

 
//console.log(longest.length);
longest_sequence=longest.trim().length;

matrix=[];

for(j=0;j<patt.length;j++) {
//
if(patt[j]!=longest) {


cleaned=patt[j]+spacer.repeat(longest.length-patt[j].length);
cleaned=cleaned.substr(-longest_sequence);
}
else {
cleaned=longest.trim();
}
matrix.push(cleaned);
}
//console.log(matrix.join('\n'));


cells=[];
for(i=0;i<matrix.length;i++)  {


cells.push(matrix[i].split(''));
$('table.small').append('<tr>');
}

$( "table.small tr" ).each(function( index ) {
for(j=0;j<cells[index].length;j++) {
$(this).append('<td>'+cells[index][j]+'</td>');
 }
});



data=$('.two').text().replace(/ /g,spacer).split('\n');
data=data.filter(function(val){
   if(val.indexOf('+')>=1) {
   return val;
   }
});

data = data.map(function(x){
   return x.slice(2);
});

//console.log(data);
//console.log(data.join('\n'));

cells=[];
for(i=0;i<data.length;i++)  {


cells.push(data[i].split(''));
$('table.big').append('<tr>');
}

$( "table.big tr" ).each(function( index ) {
for(j=0;j<cells[index].length;j++) {
$(this).append('<td>'+cells[index][j]+'</td>');
 }
});

//comparing!!!
pattern_arr=[];
$("table.small tr").each(function() {
pattern_arr.push($(this).children().text().trim())
});
function arraysEqual(a1,a2) {
    /* WARNING: arrays must not contain {objects} or behavior may be undefined */
   // console.log(JSON.stringify(a1)+':'+JSON.stringify(a2));
   // console.log('________________________________________');
    return JSON.stringify(a1)==JSON.stringify(a2);
}

count=-1;
timer=setInterval(function(){ 
count++;
sliced_arr=[];
slices=[];
$( "table.big tr" ).each(function( index ) { 
$(this).children('td').removeClass('search');
sliced=$(this).children('td').slice( count,count+longest_sequence );
slices.push(sliced);
$(sliced).addClass('search');



sliced_arr.push($(sliced).text().trim());




if(arraysEqual(pattern_arr,sliced_arr)) {



//$(sliced).addClass('found').removeClass('search');

$.each( slices, function( key, value ) {
$(this).addClass('found').removeClass('search');
});
//$(slices).addClass('found').removeClass('search');

$('#status').text('Found!');





clearInterval(timer);
 }
 
for(i=0;i<sliced_arr.length;i++)
 if(sliced_arr[i]=="") {

  clearInterval(timer);

$('#status').text('Not found!');
 break;

 }



});
}, 1000);
Run Code Online (Sandbox Code Playgroud)
.one, .two {
  font-size:22px;
}

table.big {
  border:1px solid #666;
padding:0;
  border-collapse:collapse;
}
table.big td {
  border:1px solid #666;
 
  padding:5px;
  margin:0;
}

table.small {
  border:1px solid red;
padding:0;
  border-collapse:collapse;
}
table.small td {
  border:1px solid red;
 
  padding:5px;
  margin:0;
}

.found {
  font-weight:bold;
  color:white;
  background:green;
}
.search {
  font-weight:bold;
  color:white;
  background:orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one"><pre>
   +
  +++
   +
 </pre></div>
<table class="small">

</table>
<div class="two"><pre>
  + +   ++++  + ++  + + +
  + ++ +++ + +++ ++ + +++
  + ++ + + ++ + + + + ++ 
</pre></div>

<table class="big">

</table>
<div id="status">
</div>
Run Code Online (Sandbox Code Playgroud)


Iva*_*aer 8

@ 2619的一篇文章显示了对Bliffoscope问题的兴趣.鉴于div.onediv.two,以固定宽度字体,ascii艺术风格的文本内容是拼凑在一起的图片+,意味着活动像素,并且" " (space) inactive. The idea is to find in which position we could place div.onediv.two,所以这两个模式的形成更多的交叉点.我只考虑两个给定图像的有效像素的坐标的交点.

在此示例中,+替换o为突出显示每个匹配的交叉点.canvas可以在此处找到使用的简化版本.

在下面的SO片段JSFiddle演示中,单击NextPrevious链接,或按键盘上的箭头按钮,浏览匹配项.

_main.best_positions() 返回每个可能叠加的交叉点数,具有任何误差容限,按交叉点数排序(首先匹配更多).

var PatternFinder;

PatternFinder = (function(win, doc, undefined) {
  'use strict';

  var _main = {

    selectors: {
      object_1_pattern: ".one",
      background_pattern: ".two",
      results: ".three",
      next_button: ".next",
      previous_button: ".previous",
      match_score: ".intersecting_coords",
      match_nr: ".match_nr",
    },
    cache: {
      object_text_string: '',
      context_text_string: ''
    },
    init: function() {

      _main.cache.object_text_string = $(_main.selectors.object_1_pattern).text();
      _main.cache.context_text_string = $(_main.selectors.background_pattern).text();

      // Parse our images from the text strings.
      _main.serialized_context = _main.serialize_map(_main.cache.context_text_string);
      _main.serialized_object = _main.serialize_map(_main.cache.object_text_string);

      // Find the position of the object with larger amount of intersecting coordinates
      _main.best_positions = _main.get_best_position(_main.serialized_context, _main.serialized_object);
      _main.current_result = _main.best_positions.length - 1;

      // Draw initial results
      _main.print_output(_main.current_result);

      // Handle user input
      $(_main.selectors.next_button).click(function() {
        _main.current_result -= 1;
        _main.print_output();
      });
      $(_main.selectors.previous_button).click(function() {
        _main.current_result += 1;
        _main.print_output();
      });
      // Keyboard: Arrow keys
      $(document).keydown(function(e) {
        switch (e.which) {
          case 37:
            { // left
              _main.current_result += 1;
              _main.print_output();
              break;
            }
          case 39:
            { // right
              _main.current_result -= 1;
              _main.print_output();
              break;
            }
          default:
            return;
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
      });
    },

    // Highlight an intersection.
    // Replace "+" by "o" in coords _x, _y.
    highlight_match: function(_x, _y, background) {
      var x = 0,
        y = 0,
        i = 0,
        output = "",
        c;
      for (i = 0; i < background.length; i += 1) {
        c = background[i];
        if (c == "+" && x == _x && y == _y) {
          output = output + "o";
        } else {
          output = output + c;
        }
        x += 1;
        if (c == "\n") {
          x = 0;
          y += 1;
        }
      }

      return output;
    },

    // Receive the translated serialized object,
    // and the original text string for the background.
    // Return the background text string, with the matches 
    // between it and serialized_object highlighted.
    merge_and_deserialize: function(serialized_object, background) {
      var i;
      for (i = serialized_object.length - 1; i >= 0; i--) {
        background = _main.highlight_match(serialized_object[i][0], serialized_object[i][1], background);
      }
      return background;
    },

    // Receive a text string like the one from the Stack Overflow ticket, 
    // return an array of coordinates of filled in pixels (+ or space).
    serialize_map: function(char_map) {
      var x = 0,
        y = 0,
        c,
        i,
        map = [];
      for (i = 0; i < char_map.length; i += 1) {
        c = char_map[i];
        if (c == "+") {
          map.push([x, y]);
        }
        x += 1;
        if (c == "\n") {
          x = 0;
          y += 1;
        }
      }
      return map;
    },

    // Find number of intersections between two images (that's where the magic happens).
    // Found here: https://gist.github.com/lovasoa/3361645
    array_intersect: function() {
      var a, d, b, e, h = [],
        l = [],
        f = {},
        g;
      g = arguments.length - 1;
      b = arguments[0].length;
      for (a = d = 0; a <= g; a += 1) {
        e = arguments[a].length, e < b && (d = a, b = e);
      }
      for (a = 0; a <= g; a += 1) {
        e = a === d ? 0 : a || d;
        b = arguments[e].length;
        for (l = 0; l < b; l += 1) {
          var k = arguments[e][l];
          f[k] === a - 1 ? a === g ? (h.push(k), f[k] = 0) : f[k] = a : 0 === a && (f[k] = 0);
        }
      }
      return h;
    },

    // Translate the coordinates of a serialized image.
    translate: function(coords, ix, iy) {
      return [coords[0] + ix, coords[1] + iy];
    },

    // Find in which position the object has more intersections with the background.
    get_best_position: function(context, object) {

      // Calculate image dimensions
      var context_width = context.sort(function(a, b) {
          return b[0] - a[0];
        })[0][0],
        context_height = context.sort(function(a, b) {
          return b[1] - a[1];
        })[0][1],
        object_width = object.sort(function(a, b) {
          return b[0] - a[0];
        })[0][0],
        object_height = object.sort(function(a, b) {
          return b[1] - a[1];
        })[0][1];
      // Swipe context, store amount of matches for each patch position.
      var similaritudes = [],
        cx, cy, intersection, translated_object;

      for (cx = -object_width; cx < context_width; cx += 1) {
        for (cy = -object_height; cy < context_height; cy += 1) {
          translated_object = object.map(function(coords) {
            return _main.translate(coords, cx, cy);
          });

          intersection = _main.array_intersect(context, translated_object);

          if (intersection.length > 0) {
            similaritudes.push({
              coords: [cx, cy],
              similaritudes: intersection.length
            });
          }

        }
      }
      // Return coords,
      // sorted by those for which number of matches was greater.
      return similaritudes.sort(function(a, b) {
        return a.similaritudes - b.similaritudes;
      });
    },

    print_output: function() {

      var positioned_object;

      // Get the coordinates of one of our matches.
      _main.current_result = Math.max(_main.current_result, 1);
      _main.current_result = Math.min(_main.current_result, _main.best_positions.length - 1);

      var score = _main.best_positions.slice(_main.current_result)[0].similaritudes;
      var best_position = _main.best_positions.slice(_main.current_result)[0].coords;

      // Translate our image patch to the position defined by _main.current_result.
      positioned_object = _main.serialized_object.map(function(coords) {
        return _main.translate(coords, best_position[0], best_position[1]);
      });

      // Produce merged images (background after replace).
      var final_image = _main.merge_and_deserialize(positioned_object, _main.cache.context_text_string);
      // Print image and information
      $(_main.selectors.results).text(final_image);
      $(_main.selectors.match_score).text(score);
      $(_main.selectors.match_nr).text(_main.best_positions.length - _main.current_result);
    }

  };

  // Expose methods
  _main.public_methods = {
    init: _main.init,
  };
  return _main.public_methods;

}(window, document));

PatternFinder.init();
Run Code Online (Sandbox Code Playgroud)
.one,
.two {
  display: none;
}
.three {
  white-space: pre;
  font-family: "Lucida Console", Monaco, "Courier New", Courier, monospace;
  margin: 0 0 20px 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">
    +
   +++
    +
</div>
<div class="two">
    + +   ++++  + ++  + + +
    + ++ +++ + +++ ++ + +++
    + ++ + + ++ + + + + ++ 
</div>
<h3>Match: <span class="match_nr"></span></h3> 
<h5>Intersecting coordinates: <span class="intersecting_coords"></span></h5>
<div class="three"></div>
<nav>
<a class="previous" href="#">Previous</a>
<a class="next" href="#">Next</a>
</nav>
<p><sub>Click Next and Previous or use the keyboard arrows to see other possible matches.</sub></p>
Run Code Online (Sandbox Code Playgroud)