转换jQuery代码以检测具有特定类到Native JavaScript的链接的点击

时间:2016-09-06 20:20:25

标签: javascript jquery

好的,所以我可以使用以下代码轻松地使用jQuery实现我想要做的事情:

<script type="text/javascript">
// <![CDATA[
  $('.pnTrig').on('click', function(e){

    e.preventDefault();
    var id = $(this).attr('href').split("_").pop(); // get last character of string
    console.log(id); // check correct character is returned
    P7_TP3ctrl('p7TP3_1',id); // controls to show accordian panels    

  });
// ]]>
</script>

我希望有人向我展示如何将此jQuery代码转换为本机JavaScript。

1 个答案:

答案 0 :(得分:1)

这是一个记录在案的vanilla Javascript版本。

function clickHandler(event) {
  // execute preventDefault() if don't want the link to be followed (default browser behavior)
  event.preventDefault();

  // get the event target (what `this` would refer to in jQuery) 
  var target = event.target;
  // same as before
  var id = target.href.split('_').pop();
  // same as before
  P7_TP3ctrl('P7_TP3', id);
}

// get all elements with `pnTrig` class
var triggers = document.querySelectorAll('.pnTrig');

// apply the event handler to all matching elements
for (var i = 0; i < triggers.length; i++) {
  // attach the event handler (don't define the event handling function here)
  triggers[i].addEventListener('click', clickHandler, false);
}

function P7_TP3ctrl(label, id) {
  console.log("Clicked id: ", id);
}
<a href="/foo/some_id_1" class="pnTrig">Link One</a>
<a href="/foo/some_id_2" class="pnTrig">Link Two</a>