JQuery.each () with string

How to use jQuery.each () in a string


// For Exmaple

var mystring = '<div> bleh content </div> <div> bleh content </div>';

$('div', mystring).each(function(e) {
  alert('do something');
});

// Does the above code not trigger a warning for every div in a row? I'm not sure why?

+5
source share
2 answers

As you do this, you are looking for elements divinside the transferred elements. Basically equivalent to execution .find().

You want filter()one that will filter the top-level items in the collection you submitted.

Check here: http://jsfiddle.net/u5uDg/

var mystring = '<div> bleh content </div> <div> bleh content </div>';

$(mystring).filter('div').each(function(e) {
    alert('do something');
});

If you want to use your approach, you need to provide the elements with a divparent element on which jQuery can search.

http://jsfiddle.net/u5uDg/1/

      // Added parent <div> element
var mystring = '<div><div> bleh content </div> <div> bleh content </div></div>';

$('div', mystring).each(function(e) {
  alert('do something');
});

.each() setTimeout() , , .

http://jsfiddle.net/u5uDg/6/

var mystring = '<div> bleh content </div> <div> bleh content </div>';

   // Get the length
var length = $(mystring).filter('div').length;

$(mystring).filter('div').each(function(e) {
    // setTimeout is used to delay code from executing.
    // Here we multiply e (which is the index of the current 
    //   iteration) by 2000 milliseconds, so each iteration
    //   is delayed by an additional 2000ms
    (function(th) {
        setTimeout(function() {
                 alert($(th).text());
                 if(!--length) { alert('done'); } // alert if done
        }, e * 2000);
    }(this));
});​
+7

jQuery .

div , divs javascript. html:

<div class="mystring">bleh content</div>
<div class="mystring">blehhh content</div>

script , :

$('div.mystring').each(function(e) {
  alert('do something');
});

mystring, :

var mystring = '<div class="mystring">bleh content</div><div class="mystring">blehhh content</div>';
$.each(mystring, function(e) {
  alert('do something');
});
+1

All Articles