如何在字符串上使用 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 可以在其上执行查找。
// 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()
中的代码,并通过乘以当前迭代次数除以您想要延迟的毫秒数。
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/