如何将多个参数传递给一个函数?

时间:2019-06-07 17:39:05

标签: javascript

我正在为一个学校项目工作,我试图在一个函数中使用2个参数,但是它们来自2个不同的函数。我不知道如何同时使用它们。

我想做的是实际使用showCityInfo函数handleClickImg中的代码,但是为此,我需要数据“ city” 从功能getCityInfo传递到showCityInfo上,该数据是从我的php收集的。

因此,简而言之,我想在函数中使用数据'city'和'marker(= e.currentTarget)'来执行以下以粗体显示的代码

{
  const init = () => {

    let radiobutton = document.querySelectorAll('.radio_button');
    radiobutton.forEach(r => {
      r.addEventListener("change", changeOpacity);
      let $heart = document.querySelectorAll('.sidebar > svg');

      $heart.forEach(h => {
        h.addEventListener('click', changeColor);
      })

      document.documentElement.classList.add('has-js');

      const $input = document.querySelector(`.world_form`);
      console.log($input);
      if ($input) {
        $input.addEventListener(`change`, handleChangeFilter);
      }
    });

    $markers = document.querySelectorAll('.world_map > img');
    console.log($markers);
    $markers.forEach(marker => {
      marker.addEventListener('click', handleClickImg);
    })

  }

  const handleChangeFilter = e => {
    const alignment = e.target.value;
    console.log(alignment);
    const path = window.location.href.split(`?`)[0];
    const qs = `?alignment=${alignment}`;
    getCityInfo(`${path}${qs}`);
  };

  const getCityInfo = async url => {
    console.log(url);
    const response = await fetch(url, {
      headers: new Headers({
        Accept: 'application/json'
      })
    });
    const city = await response.json();
    console.log(city);
    window.history.pushState({}, ``, url);
    showCityInfo(city);
  };
  const showCityInfo = city => { **
    const $parent = document.querySelector(`.contact_wrapper`);
    $parent.innerHTML = ``;
    $parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}@hotmail.com</p>
    <p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>` **
  };

  const handleClickImg = e => {
    marker = e.currentTarget;
    console.log(marker);



    if (marker.id == city.city_code) {

    }
  }

1 个答案:

答案 0 :(得分:0)

如果您一次只需要比较一个城市和一个标记,我想您应该做的是在函数之外声明两个全局变量以存储城市和标记数据,并能够在任何地方访问和比较它们

//...

let city, marker;

const getCityInfo = async url => {
  console.log(url);
  const response = await fetch(url, {
    headers: new Headers({
      Accept: 'application/json'
    })
  });
  city = await response.json();
  console.log(city);
  window.history.pushState({}, ``, url);
  showCityInfo();
};

const showCityInfo = () => {
  const $parent = document.querySelector(`.contact_wrapper`);
  $parent.innerHTML = ``;
  $parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}@hotmail.com</p><p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>`
};

const handleClickImg = e => {
  marker = e.currentTarget;
  console.log(marker);

  if (marker.id == city.city_code) {

  }
}