简体   繁体   中英

Loop through HTML content and return values as global variables

I would like to know if it is possible to create var s in JavaScript dynamically and return them into a global variables. Example:

<div id="parent">
  <span class="span_1">content</span>
  <span class="span_2">another</span>
  <span class="span_3">yup content</span>
</div>

and following function:

function getContent() {
  var divs = $('#parent').children('span').length;
  for(var i = 1; i < divs; i++) {
    jQuery('.span_'+i).html(); //this returned as global variables for each span
  }
}

as you can see I want to loop through the spans HTML and want to have variables with content of each span as global variables. How would I do that?

Thanks

You can use .map() this way:

var globalVar; // javascript set the value as "undefined".

Then in your function do this:

function getContent() {
     globalVar = $('#parent span').map(function(){
                     return $(this).text();
                 }).get();

   //results in --> globalVar = ["content", "another", "yup content"]

}

.map() creates an array with the collection of your selectors and make sure to chain it with .get() to get the collection in the array.

You can get an array having the content of span elements using jQuery map() method as shown below:

 var spanContents = $("#parent span").map(function(i, elm) { return $(elm).text(); // or html() if applicable }).get(); console.log(spanContents); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="parent"> <span class="span_1">content</span> <span class="span_2">another</span> <span class="span_3">yup content</span> </div> 

As well as iterating through that loop (that should start in 1 like Jai said), you can use "Attribute starts with" selector .

For example:

$('#parent span[class^="span_"])

will return an array with each span having class beginning with 'span_' inside your #parent element.

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