Jquery:获取函数的返回值

时间:2016-04-24 09:33:10

标签: javascript jquery return-value

我想用jquery创建一个基本的泛型函数,将html列表的所有元素放入一个数组中。一切似乎都没问题,但我遇到了一些问题,以获得返回值。我知道这是一个基本问题所以我希望你能帮助我解决它。

  <script>
        function listeToArrayById(idListe){ 
            $(function(){
                var listChildren = $("#" + idListe).children(); //puts all li children in var listChildren
                var arrayListChildren = [];
                $.each(listChildren, function(key, value){
                    arrayListChildren.push($(this).text());
                })
                return arrayListChildren; // here it's ok arrayListChildren = ["a", "b", "c"] 
            })
        }
        var ulChildren = listeToArrayById("list1");
        window.console.log(ulChildren); // here is my problem because ulChildren is undefined ... I should get an array ["a", "b", "c"]
    </script>
</head>
<body>
    <ul id="list1">
        <li>a</li>
        <li>b</li>
        <li>c</li>
    </ul>
    </body>

1 个答案:

答案 0 :(得分:4)

您以错误的方式使用 document ready handler

function listeToArrayById(idListe){ 
     var listChildren = $("#" + idListe).children();
     var arrayListChildren = [];
     $.each(listChildren, function(key, value){
        arrayListChildren.push($(this).text());
     })
     return arrayListChildren; // here it's ok arrayListChildren = ["a", "b", "c"] 
}

$(function(){
  var ulChildren = listeToArrayById("list1");
  console.log(ulChildren); 
});

您可以像下面一样简化代码,

function listeToArrayById(idListe){ 
     return $("#" + idListe).children().map(function(){
           return this.textContent
     }).get();
}