2016-11-21 74 views
0

我试图达到作为数组元素的子函数。如何在jquery中运行一个数组元素的子函数

在下面的例子中,我们可以到达name财产,如window['name']

但是,如果属性是一个函数,它不能像这样调用。我试图做的是在.each函数中,如果item是一个函数运行的函数。我怎样才能做到这一点 ?。

$(document).ready(function() { 

    var human = { 
    name: 'Emin', 
    surname: 'Çiftçi', 
    job: 'Software Developer', 
    func: function() { 
     alert(name + ' ' + surname + ', ' + job); 
    } 
    }; 

    $.each(human, function(index, item) { 
    //if(item is a function) { 
    // run the function 
    //} 
    $('<div>').text(index + ': ' + item).appendTo('#deneme'); 

    }); 
}); 
+0

正如我所看到的,你使用jquery每个似乎都不错,尝试做一个控制台日志的变种,并看到控制台输出并告诉我们 –

回答

2

使用typeof

PS:您还需要修复的名字,姓氏和工作在警报

$(document).ready(function() { 
 

 
    var human = { 
 
    name: 'Emin', 
 
    surname: 'Çiftçi', 
 
    job: 'Software Developer', 
 
    func: function() { 
 
     alert(human.name + ' ' + human.surname + ', ' + human.job); 
 
    } 
 
    }; 
 

 
    $.each(human, function(name, item) { 
 
    console.log(typeof item); 
 
    if (typeof item == "function") item(); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

+0

谢谢先生,工作。 'typeof'保存一天:) 编辑:是的,我现在意识到我必须改变它们。谢谢。 –

1

您可以使用typeof

if(typeof item === 'function'){ 
     item(); // run it 
} 
+1

仍然错误。已经回答了 – mplungjan

+0

嗯,这是正确的!很难被移动...;) – Jai

+0

我的意思是你的是正确的... – Jai

相关问题