如何反转功能

时间:2015-12-09 00:25:32

标签: jquery

使用点系统为每个元素分配点,并在一组搜索结果中匹配内容。当我比较.per-results.myself的内容时它很有效,但是当我从.myself到.per-result进行比较时它不起作用。

如果反转,它仍会分配点数,但是当它应该不同时,它会为所有.per-result分配相同数量的点数。

$(function() {
      $('.per-result').each(function() {
        var $matches = $('span', this).filter(function() { // Each item
            var texts = $(this).text();
            return $('.myself span').filter(function() { // Are there matches in .three?
                return $(this).text() === texts;
            }).length > 0;
        }).length;
        $('.theyRate', this).text(('They score me ' + $matches * 6 + ' Points' ));
    });
  
  
  
  //Reversing the point system
  
        var $matches = $('.myself span', this).filter(function() { // Each item
            var texts = $(this).text();
            return $('.per-result span').filter(function() { // Are there matches in .three?
                return $(this).text() === texts;
            }).length > 0;
        }).length;
        $('.iRate').text(('I score them ' + $matches * 6 + ' Points' ));

  
});
div {
  display: inline-block;
  width: 100%;
  margin-bottom: 50px;
  font-family: calibri;
}

div span {
  display: block;
  width: 100%;
}

.theyRate {
  color: green;
  font-weight: bold;
  background: white;
  border-bottom: solid 1px #444;
}

.iRate {
  color: orange;
    font-weight: bold;
  background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div class="per-result">
<h2>Result 1</h2>

<span>Utmost inportant</span>
<span>Utmost inportant</span>

<span>Slightly inportant</span>
<span>Slightly inportant</span>
<span>Slightly inportant</span>
				<span class="theyRate"></span>
						<span class="iRate"></span>
  </div>


<div class="per-result">
<h2>Result 2</h2>
<span>Utmost inportant</span>
<span>Utmost inportant</span>
<span>Utmost inportant</span>

<span>Slightly inportant</span>


	<span class="theyRate"></span>
						<span class="iRate"></span>
</div>


<div class="per-result">
<h2>Result 3</h2>
<span>Utmost inportant</span>


<span>Slightly inportant</span>

	<span class="theyRate"></span>
						<span class="iRate"></span>


</div>





<div class="myself">
<h1>Searchman</h1>
<span>Utmost inportant</span>
<span>Utmost inportant</span>
<span>Utmost inportant</span>

<span>Slightly inportant</span>
<span>Slightly inportant</span>
<span>Slightly inportant</span>

</div>

Link to fiddle

1 个答案:

答案 0 :(得分:0)

你总是得到相同的iRate答案的原因是因为'反向'代码循环遍历每个'我自己'的跨度并检查所有'每个结果'跨度中是否有任何匹配。它不像第一个功能那样限制在每个“每个结果”部分。此外,它只需要在整个结果集中找到一个匹配项匹配。因此,所有六个“我自己”的跨度都将被视为一个点。

return $('.per-result span').filter(function() 

此外,您只需一次通话即可同时更新所有三个$('。iRate')。文本。

$('.iRate').text(('I score them ' + $matches * 6 + ' Points' ));

理想情况下,您可以单独更新每个部分的iRate。