测试 .each() 内部并突破
我在这里尝试做的是使用 jquery .each() 循环遍历图像列表,并测试我传递给函数的 src 是否已存在于列表中。如果没有我想添加它,如果有我不想做任何事情。我应该在哪里添加添加新图像的代码,记住我只想在each()迭代结束后执行此操作
这是到目前为止我所拥有的,
function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar
var imgReturn = $('ul.friendImages li img').each(function(){
var currentImageSrc = $(this).attr('src');
if(currentImageSrc == imageSrc){
return false;
}
});
if(imgReturn != false){//does this make sense?
//I'll add an new image, (I can work out to do this bit myself)
}
}
我是javascript和jquery的新手,所以我可能出了问题句法。 任何反馈将不胜感激。
What I'm trying to do here is loop through a list of images with jquery .each() and test if the src that I'm passing to the function already exists inside the list. If it doesn't I want to add it, if does I don't want to do anything. Where do I put the code to add a new image baring in mind I only want to do this after the each() iterations are over
Here's what I have so far
function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar
var imgReturn = $('ul.friendImages li img').each(function(){
var currentImageSrc = $(this).attr('src');
if(currentImageSrc == imageSrc){
return false;
}
});
if(imgReturn != false){//does this make sense?
//I'll add an new image, (I can work out to do this bit myself)
}
}
I'm new to javascript and jquery so I may have gone wrong with the syntax.
Any feedback would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以跳过循环,只使用 jQuery
[attribute="value"]
选择器:您无法从
$.each
返回值,因为它始终返回用于调用链的 jQuery 对象。但是,返回 true/false 确实具有特殊含义:返回false
的行为类似于break;
语句并且迭代停止,而返回true
的行为类似于continue
语句,提前停止当前迭代并继续下一个迭代。You can skip the loop and just find all images with the src attribute you're looking for, using the jQuery
[attribute="value"]
selector:You can't return values from
$.each
as it always returns the jQuery object for call chaining. However, returning true/false does have special meaning: Returningfalse
behaves like abreak;
statement and iteration stops, while returningtrue
behaves like acontinue
statement, stopping the current iteration early and continuing to the next.您可以避免所有额外的内容并直接查询。
You can avoid all the extra stuff and query it directly.