将jQuery代码转换为纯JavaScript

时间:2016-12-24 03:07:02

标签: javascript jquery

我在jQuery中转换以下代码时遇到问题,有人可以给我看一个例子吗?

$('li').click(function() {
    window.location = $(this).find(':first-child').attr('href');
});​​​​​​​​​

2 个答案:

答案 0 :(得分:3)

详情在Snippet中发表了评论。通过将事件侦听器添加到父级,我们可以利用捕获,目标,冒泡事件阶段来找出实际单击的元素。这需要一个简单的事件监听器的简单投资,而不是一个添加几个事件监听器的循环,这有点过分。此过程称为event delegation

<强>段

&#13;
&#13;
/*$('li').click(function() {
    window.location = $(this).find(':first-child').attr('href');
});*/

//reference the parent of all li
var list = document.querySelector('ul');

//add event listener to ul that fires on any click 
//on any of it's children li or itself

list.addEventListener('click', function(e) {

  // if ATM the actual element that is clicked isn't the ul,
  // then declare that the e.target (it's the anchor that's 
  // clicked because it's the last element on the event chain)

  if (e.target !== e.currentTarget) {
    
    // Save the the e.target's href in a var tgt
    var tgt = e.target.href;
   
    // Assign your new location as the value of tgt
    window.location = tgt;
  }
console.log(tgt);
}, false);
&#13;
<ul>
  <li><a href='http://example.com'>GO</a>
  </li>
  <li><a href='http://stackoverflow.com'>GO</a>
  </li>
  <li><a href='http://www.w3shools.com'>GO</a>
  </li>
  <li><a href='http://example.com'>GO</a>
  </li>
  <li><a href='https://yahoo.com'>GO</a>
  </li>
  <li><a href='http://example.com'>GO</a>
  </li>
  <li><a href='https://developer.mozilla.org.com'>GO</a>
  </li>
  <li><a href='http://example.com'>GO</a>
  </li>
  <li><a href='https://google.com'>GO</a>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试与jQuery建立联系的一个非常有用的工具是:http://youmightnotneedjquery.com/

// Grab all list items on the page
var listItems = new Array(document.getElementsByTagName('li'));

// function that will be assigned when the list item is clicked
function getHref(){
  // grab the first child's href
  window.location = this.querySelector(':first-child').getAttribute('href');
}

// loop through the list items and assign the function
for(var i = 0; i < listItems.length; i++) {
  listItems[i][0].addEventListener('click', getHref);
}
<ul>
    <li>
      <a href="http://google.ca">Google</a>  
    </li>
    <li>
      <a href="http://stackoverflow.com">Stack Overflow</a>  
    </li>
</ul>