为 Google 标签管理器翻译 jQuery 普通代码 JavaScript

Translate jQuery code in plain JavaScript for Google Tag Manager

我需要将此 jQuery 代码翻译成 javascript 以便在 Google 跟踪代码管理器中使用,但我在翻译时遇到了一些问题:

$('.book-wrapper').click(function() {return( $('.book-title', this).text() )});

非常感谢任何帮助。谢谢!

像下面这样的东西应该适合你

<div class="book-wrapper">Click here to see name of the book</div>
<div class="book-title">Lord of the Rings</div>


<script type="text/javascript">

  var bookWrapper = document.getElementsByClassName('book-wrapper');

  for (var x = 0; x < bookWrapper.length; x++) {
     bookWrapper[x].addEventListener('click', getText);
  }

  function getText() {
    alert(document.getElementsByClassName('book-title')[0].innerHTML);
    return document.getElementsByClassName('book-title')[0].innerHTML;
  }

</script>

看起来像这样,我认为:

    var els = document.querySelector('.book-wrapper');

    for (var ix = 0; ix < els.length; ix++) {
      els[ix].addEventListener('click', getText);
    }

    function getText(e) {
      var titles = e.target.querySelector('.book-title');
      return titles[0].innerText || null;
    }
<div class="book-wrapper">
  <div class="book-title">A Tale of Two Cities</div>
</div>

使用document.querySelectorAll()获取所有元素book-wrapper class:

var wrappers= document.querySelectorAll('.book-wrapper');

遍历 collection,添加点击处理程序。使用this.querySelector()抓取点击的标题book-wrapper:

for(var i = 0 ; i < wrappers.length ; i++) {
  wrappers[i].addEventListener('click', function(e) {
    var title= this.querySelector('.book-title').textContent;
    console.log(title);
    return title;
  });
}

var wrappers= document.querySelectorAll('.book-wrapper');

for(var i = 0 ; i < wrappers.length ; i++) {
  wrappers[i].addEventListener('click', function(e) {
    var title= this.querySelector('.book-title').textContent;
    console.log(title);
    return title;
  });
}
.book-wrapper {
  box-shadow: 10px 10px 5px 0px rgba(0,0,0,0.75);
  margin-bottom: 2em;
  border: 1px solid #666;
}
<div class="book-wrapper">
  <div class="book-title">The Little Prince</div>
  <div>
    This is the story about a little prince.
  </div>
</div>

<div class="book-wrapper">
  <div class="book-title">The Little Mermaid</div>
  <div>
    This is the story about a little mermaid.
  </div>
</div>