为什么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;
}
})
}
})
}
答案 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 强>