jQuery的每个()用绳子 [英] jQuery .each() with string

查看:120
本文介绍了jQuery的每个()用绳子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用jQuery的每个()一个字符串

How do I use jQuery .each() on a string



// For Exmaple

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

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

//上面的code心不是发动警报字符串中的每个div?林不知道为什么?

// the above code isnt launching an alert for each div in the string? Im not sure why?

推荐答案

你这样做的方式,你正在寻找 DIV 传入的元素中的元素基本上相当于做了的.find()

The way you're doing it, you're searching for div elements inside the elements passed in. Basically equivalent of doing a .find().

你想要的是过滤器()将筛选过你通过集合中的顶级元素。

What you want is filter() which will filter over the top level elements in the collection you passed.

在这里测试: http://jsfiddle.net/u5uDg/

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

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

如果你想用你的方法,你就需要给 DIV 元素的父上jQuery的可以进行查找。

If you wanted to use your approach, you would need to give the div elements a parent on which jQuery can perform the find.

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');
});


按照要求在您的评论,您可以延迟执行的code。在每个()使用的setTimeout(),到达每一个的持续时间由您要延迟的毫秒数乘以当前迭代次数。


As requested in your comment, you can delay execution of the code in the .each() using setTimeout() and arriving at the duration of each by multiplying the current iteration number by the number of milliseconds you want to delay.

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));
});​

这篇关于jQuery的每个()用绳子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆