如何将内联onClick代码替换为addEventListner?

时间:2019-06-17 16:18:15

标签: javascript onclick addeventlistener

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<!-- Tab content -->
<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

给出的代码利用了旧方法和ES5。但是,我无法通过使用addEventListner在ES6中进行转换。

我在onClick()函数中使用诸如不同城市名称之类的参数时遇到问题。enter code here

3 个答案:

答案 0 :(得分:1)

我认为您的评论没有错,但实际上页面上没有id为“ defaultOpen”的元素,因此这就是错误的出处。

答案 1 :(得分:1)

对于JavaScript部分:

let elements = document.querySelectorAll('.tablinks');
for(var i = 0;i < elements.length; i++){
    elements[i].addEventListener('click', function(){
        var target = elements[i].getAttribute('data-target');
        openCity(evt, document.querySelector(target));
    }, false);
}

编辑HTML使其如下所示:

<div class="tab">
  <button class="tablinks" data-target="#London">London</button>
  <button class="tablinks" data-target="#Paris">Paris</button>
  <button class="tablinks" data-target="#Tokyo">Tokyo</button>
</div>

我们为什么使用querySelectorquerySelectorAll?这样我们就可以使用任何CSS选择器来定位标签。例如。 #tabs .pages

我们为什么使用data-target?这样我们就可以在元素主体中键入所需的任何内容。

答案 2 :(得分:0)

尚未测试过,但这可能有效:

 tablinks = document.getElementsByClassName("tablinks");
 for (i = 0; i < tablinks.length; i++) {
    tablinks[i].removeAttribute('onclick');
    tablinks[i].addEventListener('click', function() { 
       openCity(evt, evt.currentTarget.innerHTML());
    }, false);
};