使用jQuery

时间:2015-12-30 13:01:42

标签: javascript jquery html ajax getelementbyid



$(document).ready(function() {
 $.ajax({
        type: "POST",
        url: 'some/url',
        data: {
              'name':'myname'   
              },
         success: function (result) {
      
          var result = ["student", "test"];
          var length = result.length;

          for (var i = 0; i < length; i++) {

            var datastores = result;

            $('#data_stores').append(
            "<div class='col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore' id=" +             datastores[i] + "> </div>");

          }
      }
 })
  var ids = $('#data_stores').children().map(function(){ return this.id }).get();


  $('<pre>').appendTo('body').text(JSON.stringify(ids));

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_stores">
</div>
&#13;
&#13;
&#13;

<div id="data_stores">

 <div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="students">

   //Some other codes here

 </div>

 <div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="teachers">

   //Some other codes here

 </div>

</div>

这是我的HTML中的一段代码。 data_stores下的内部div使用jquery创建。子div的ID是AJAX请求的结果,并在成功时分配。

问题是,我需要子div的ID值用于另一个AJAX调用。

我运行了以下内容:

console.log($("#data_stores"));

我得到的输出与上面相同。

但是,

console.log($("#data_stores").find('.datastore'));
  

[prevObject:m.fn.init [1],context:document,selector:&#34; #data_stores   .datstore&#34;]

但是,当访问孩子时,它说元素是未定义的。

我需要在

上进行两次AJAX调用
$(document).ready(function() {
})

1 个答案:

答案 0 :(得分:1)

像这样使用children有效:

var ids = $('#data_stores').children().map(function(){ return this.id }).get();

&#13;
&#13;
var ids = $('#data_stores').children().map(function(){ return this.id }).get();

$('<pre>').appendTo('body').text(JSON.stringify(ids));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data_stores">

 <div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="students">

   //Some other codes here

 </div>

 <div class="col-sm-8 col-md-8 col-lg-8 col-xs-8 pre-panel datastore" id="teachers">

   //Some other codes here

 </div>

</div>
&#13;
&#13;
&#13;