简体   繁体   中英

asynchronous callback function in a loop

This is kind of different situation then any other question.

I have several div elements with class and data-label attributes.

<div class='toLoad' data-label='a'></div>
<div class='toLoad' data-label='b'></div>
<div class='toLoad' data-label='c'></div>
<div class='toLoad' data-label='d'></div>

Here is the javascript:

function theData(e) {
  // What do I do here to put the data to their respective div
}

function createScript() {
  var elem = document.querySelectorAll('div.toLoad');
  for (var i = 0; i < elem.length; i++) {
    var theLabel = elem[i].getAttribute('data-label'),
      theLink = "/index/"+ theLabel +"&callback=theData",
      currentItem = elem[i],
      e = document.createElement('script');
    e.src = theLink;
    e.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(e);
  }
}

After putting the above Javascript, a script element is appended. After loading, the script returns a callback function named as theData with all content as argument. I want append the returned content to their respective div elements.

I don't know how to exactly put them in.

Assuming that callback method is available and it has two arguments data-label value (to identity which div should be populated) and the data itself

function callback( dataLabel, htmlData )
{
  $( "div[data-label='" + dataLabel + "']".html( htmlData ) );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM