无法将字符串变量传递给函数

时间:2021-03-29 21:03:15

I have a dropdown and when one of the items is clicked, I call this function:

我有一个下拉列表,当点击其中一个项目时,我调用此函数:

  onClick(type) {
    type.preventDefault();
    let query = type.target.text;
    PokeApi.pokemonType(query).then(function(data) {
      console.log(data);
    }.bind(this));
  }

The console.log returns undefined.

console.log返回undefined。

When I do this:

我这样做的时候:

  onClick(type) {
    type.preventDefault();
    let query = type.target.text;
    console.log(query);
    console.log(typeof query);
    PokeApi.pokemonType(query).then(function(data) {
      console.log(data);
    }.bind(this));
  }

The first console.log will return the text of the dropdown item. The second console.log will return string. Now, when I pass query to PokeApi.pokemonType, I can get back a 404 error from the api and the third console.log returns undefined.

第一个console.log将返回下拉项的文本。第二个console.log将返回字符串。现在,当我将查询传递给PokeApi.pokemonType时,我可以从api返回404错误,第三个console.log返回undefined。

But if I pass in the text of the dropdown directly like this:

但是,如果我像这样直接传递下拉列表的文本:

  onClick(type) {
    type.preventDefault();
    PokeApi.pokemonType("ice").then(function(data) {
      console.log(data);
    }.bind(this));
  }

Everything works perfectly fine and I get the correct object back from the api.

一切都运行得很好,我从api得到了正确的对象。

Any idea why this happening? What am I doing wrong?

知道为什么会这样吗?我究竟做错了什么?

1 个解决方案

#1


0  

You have to get the value of the dropdown selected element

您必须获取下拉列表选定元素的值

var sel = document.getElementById('myDropdown'),
var selectedText = sel.options[sel.selectedIndex].value;

#1


0  

You have to get the value of the dropdown selected element

您必须获取下拉列表选定元素的值

var sel = document.getElementById('myDropdown'),
var selectedText = sel.options[sel.selectedIndex].value;