3

我只能在 HTML 完成加载后使用以下代码获取值:

var array = $('#Stats1_totalCount strong').map(function(){
    return $(this).text()
}).get();
var vcount = '';
for (i = 0; i < array.length; i++) { 
    vcount += array[i];
}
console.log(vcount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="counter-wrapper graph-counter-wrapper" id="Stats1_totalCount">
  <span class="digit stage-0"><strong>1</strong></span>
  <span class="digit stage-0"><strong>2</strong></span>
  <span class="digit stage-0"><strong>3</strong></span>
  <span class="digit stage-0"><strong>4</strong></span>
  <span class="digit stage-0"><strong>5</strong></span>
</span>

但是 Blogger 使用 ajax 来inject counter

Counter and image will be injected later via AJAX call.

我尝试使用.ajaxStopand ajaxComplete,它们都不起作用。
如何使用 JS 获取视图计数器的值?

4

1 回答 1

0

感谢@RoryMcCrossan 的建议MutationObserver,我现在可以使用 JavaScript 获取查看计数器的值!

(function startObservation() {
  var
    /* 1) Create a MutationObserver object*/
    observer = new MutationObserver(
      function(mutations) {      
      mutationObserverCallback(mutations);
    }),  
    /* 2) Create a config object */
    config = {childList: true};
 
  /* 3) Glue'em all */
  observer.observe(Stats1_totalCount, config);
})();
function mutationObserverCallback(mutations) {
  var mutationRecord = mutations[0];
  if (mutationRecord.addedNodes[0] !== undefined) {

  var array = $('#Stats1_totalCount strong').map(function(){
    return $(this).text()
  }).get();
  var vcount = '';
  for (i = 0; i < array.length; i++) { 
    vcount += array[i];
  }
  console.log(vcount);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="counter-wrapper graph-counter-wrapper" id="Stats1_totalCount">
  <span class="digit stage-0"><strong>1</strong></span>
  <span class="digit stage-0"><strong>2</strong></span>
  <span class="digit stage-0"><strong>3</strong></span>
  <span class="digit stage-0"><strong>4</strong></span>
  <span class="digit stage-0"><strong>5</strong></span>
</span>

于 2016-12-02T14:45:48.933 回答