如何在类内的“文字模板”内添加“ onclick函数”?

这是我的第一个问题,对于任何错误或问题太傻表示抱歉。

*我有一个Class,其方法在屏幕上显示国家(地区)卡。我需要添加一个onclick函数来保存国家名称,以便可以从另一个页面访问它。我不知道是否有办法使其工作。

有什么想法吗?

class UI {
    constructor() {
         this.cardsContainer = document.querySelector("#cards-container");
     }

    showCountries(data) {
        data.forEach(country => {
            let div = ` 
            <div class="card">
                // this is the onclick function i need to access  
                <a onclick="countrySelected(${this.country.borders})"> 

                <div class="card-image">
                <img src=${country.flag} alt="">
                </div>
                <div class="card-info">
                 <h2 class="card-name"> ${country.name}</h2>
                 <p><strong>Population:</strong> ${country.population}</p>
                 <p><strong>Region:</strong> ${country.region}</p>
                 <p><strong>Capital:</strong> ${country.bogota}</p>
                </div>
                </a>
            </div>
           `;
        this.cardsContainer.innerHTML += div;
      })
    }

    //method 
    countrySelected(data) {
        sessionStorage.setItem('country',data);
    }
}
shenjie63293713 回答:如何在类内的“文字模板”内添加“ onclick函数”?

我认为country.name是唯一的。

class UI {
  constructor() {
    this.cardsContainer = document.querySelector("#cards-container");
  }

  showCountries(data) {
    data.forEach(country => {
      let div = ` 
            <div class="card">
                // this is the onclick function i need to access  
                <a id=${country.name}> 

                <div class="card-image">
                <img src=${country.flag} alt="">
                </div>
                <div class="card-info">
                 <h2 class="card-name"> ${country.name}</h2>
                 <p><strong>Population:</strong> ${country.population}</p>
                 <p><strong>Region:</strong> ${country.region}</p>
                 <p><strong>Capital:</strong> ${country.bogota}</p>
                </div>
                </a>
            </div>
           `;

      this.cardsContainer.innerHTML += div;
      document.querySelector(`a[id="${country.name}"]`)
              .addEventListener('click',() => countrySelected(country.borders));
    })
  }

  //method 
  countrySelected(data) {
    sessionStorage.setItem('country',data);
  }
}

此外,您可以参考这篇文章:Setting HTML Button`onclick` in template literal

本文链接:https://www.f2er.com/3156749.html

大家都在问