【问题标题】:How can i add an "onclick function" inside a `literal template` which is inside a Class?如何在类中的“文字模板”中添加“onclick 函数”?
【发布时间】:2019-11-07 10:35:11
【问题描述】:

如果我在这里的第一个问题,很抱歉有任何错误或问题太愚蠢。

*我有一个带有在屏幕上显示国家/地区卡的方法的类。我需要添加一个 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);
    }
}

【问题讨论】:

标签: javascript class template-literals


【解决方案1】:

我假设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

【讨论】:

  • 感谢 Max Peng!它解决了这个问题。确实,添加事件监听器比添加 onclick 函数要好得多。
  • 很高兴听到这个消息。 :D
猜你喜欢
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 2017-09-19
相关资源
最近更新 更多