带有字符串的 jQuery .each()

标签 jquery ajax string

如何在字符串上使用 jQuery .each()


// For Exmaple

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

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

//上面的代码没有为字符串中的每个 div 启动警报?我不确定为什么?

最佳答案

您执行此操作的方式是在传入的元素内搜索 div 元素。基本上相当于执行 .find()

您想要的是 filter() ,它将过滤您传递的集合中的顶级元素。

在这里测试: 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 可以在其上执行查找。

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

根据评论中的要求,您可以使用 setTimeout() 延迟执行 .each() 中的代码,并通过乘以当前迭代次数除以您想要延迟的毫秒数。

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 .each(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3153940/

相关文章:

javascript - 用。。。来代替(); jQuery 函数

php - 防止 jQuery UI 自动完成显示类似的结果

c# - 部分 View 作为 Bootstrap Modal 客户端验证不起作用

php - 是否可以直接使用 ajax 发送 php session 变量?

javascript - Java servlet 和 javascript get 请求 : multiple requests to the same servlet, 更新了游戏状态

javascript - 将 javascript 对象数组发送到 MVC4 Controller

R - 匹配两列之间的字符串

javascript - 使用 jQuery 从网页获取包含数字数据的所有元素?

python - python - 如何使用单行将列表/元组转换为python中的空格分隔字符串?

c++ - 无法初始化类型为 "std::string&"(非 const 限定)的引用