Как я могу добавить «функцию onclick» внутри «буквального шаблона», который находится внутри класса? - PullRequest
1 голос
/ 05 ноября 2019

это если мой первый вопрос здесь, так что извините за любую ошибку или если вопрос слишком глупый.

* У меня есть класс с методом, который отображает карту страны на экране. Мне нужно добавить функцию 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);
    }
}

1 Ответ

0 голосов
/ 07 ноября 2019

Я предполагаю, что 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);
  }
}

Также вы можете сослаться на этот пост: Установка HTML Button`onclick` в литерале шаблона

...