使用jquery

时间:2017-09-15 08:43:16

标签: javascript jquery

我试图通过Google Chrome控制台中的Jquery在不断更新的页面上计算图像,

我已经写了下一个剧本,但它似乎没有正常工作,如果你能帮助我,我会很高兴:

var count = 0;
window.setInterval(function() {
  $('.image .big').each(function(i, obj) {
    if ($('.box').find('img').attr("src") == "special-src/img.png") {
      count++
    } else {
      count--
    };
    $('.image .big').addClass('.done').removeClass('.image .big'); // To not count it multiple times
    console.log(count);
  });
}, 1000);

编辑: 我正在使用的HTML看起来像这样: (div正在被删除并添加)

<div class="box">
        <img src="special-src/img.png" class="image big"/>
</div>
<div class="box">
        <img src="special-src/img2.png" class="image big"/>
</div>

2 个答案:

答案 0 :(得分:0)

通过一些有创意的CSS选择器,我们可以找到您想要计算的元素。我添加了一些注释来阐明每个选择器的作用。答案应该输出数字2,因为我添加了三张特殊图像和一张普通图像。

(function() {
  var 
    count = 0,
    // Selector for finding all items with the class "box" but with the class "done".
    selectorNotProcessed = '.box:not(.done)',
    // Selector for all element with the classes "image" and "big" with a "src" attribute
    // that contains "img1.png" and that have an ancestor with the class "box" but not
    // the class "done"
    selectorSpecialNotDone = `${selectorNotProcessed} .image.big[src*="img1.png"]`,
    // Selector for all element with the classes "image" and "big" with a "src" attribute
    // that DOESN'T contain "img1.png" and that have an ancestor with the class "box" but 
    // not the class "done"    
    selectorNotSpecialNotDone = `${selectorNotProcessed} .image.big:not([src*="img1.png"])`;
  
  setInterval(function() {
    var
      // Get all the non processed special src elements.
      specialElements = document.querySelectorAll(selectorSpecialNotDone),
      // Get all the non processed non-special src elements.
      notSpecialElements = document.querySelectorAll(selectorNotSpecialNotDone);
      
    // Update the count of the number of special src elements vs non-special src elements
    count += (specialElements.length - notSpecialElements.length);
    
    // Add the done class to all the elements with the class "box" that do not yet have the
    // class "done".
    document.querySelectorAll(selectorNotProcessed).forEach(element => element.classList.add('done'));
    
    console.log(count);
  }, 1000);
})();
<div class="box">
  <img src="folder/img1.png" class="image big"/>
</div>
<div class="box">
  <img src="folder/img2.png" class="image big"/>
</div>
<div class="box">
  <img src="folder/img1.png" class="image big"/>
</div>
<div class="box">
  <img src="folder/img1.png" class="image big"/>
</div>

答案 1 :(得分:0)

结帐此link以获取动态计算图片的工作示例。

$(document).bind('DOMSubtreeModified', function () {

    console.log("document changed");
    if (totalImages !== $(".image.big").length && !disableRecounting) {
         disableRecounting = true;
         console.log("recount images..", totalImages, $(".image.big").length);
       countImages();
     }
});