为什么函数返回element.innerHTML或element.innerText是未定义的?

时间:2017-05-17 17:27:24

标签: javascript return innerhtml

为什么function(){ return element.innerHTML }会返回undefined

var demo = document.getElementById('demo');
demo.innerHTML = endangeredSpecies("Europe", "Cave bear");

function endangeredSpecies(continent, species) {
    var contin = document.querySelectorAll('[data-continent]');
  contin.forEach(function(div){
    if(div.getAttribute('data-continent') == continent){
                var children = [].slice.call(div.children);
        children.forEach(function(child) {
                    if(child.getAttribute('data-species') == species) {
                return child.innerText;
                }
            })
     }
  })
}

Fiddle

1 个答案:

答案 0 :(得分:2)

你的函数不返回任何东西,也返回里面forEach不返回值。将其分配给变量并从函数liek

返回
var demo = document.getElementById('demo');
demo.innerHTML = endangeredSpecies("Europe", "Cave bear");

function endangeredSpecies(continent, species) {
    var contin = document.querySelectorAll('[data-continent]');
  var val;
  contin.forEach(function(div){
    if(div.getAttribute('data-continent') == continent){
                var children = [].slice.call(div.children);
        children.forEach(function(child) {
                    if(child.getAttribute('data-species') == species) {
                val =  child.innerText;
                }
            })
     }
  })
  return val;
}

<强> JSFIDDLE