Jquery 选择器 .each()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5312767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery selector .each()
提问by gong
Consider the following HTML:
考虑以下 HTML:
<div id="myfavorites">
<p><button id="saveFav">Save my favorites</button> </p>
<p><a href="http://bit.ly/fzgxya">http://bit.ly/fzgxya</a> <a class="favlinks" href="#">(remove me)</a></p>
</div>
When button is pressed, I want to make a json object with all the links.
按下按钮时,我想创建一个包含所有链接的 json 对象。
$('#saveFav').click(function() {
var toSave = { "searchtext" : $('#searchText').val().trim() };
var links = {};
$('#myfavorites p').each(function(index) {
links[index] = $(this).first('a').attr('href');
});
toSave.links = links;
}
But in $('#myfavorites p').each function, $(this) isn't the pelement. I am missing something here. How can I iterate in all pand find the first aelement?
但是在 $('#myfavorites p').each 函数中, $(this) 不是p元素。我在这里遗漏了一些东西。如何遍历所有p并找到第一个a元素?
And am I construction the object correctly? I mean if I pass it to a php page, will it json_decode correctly?
我是否正确构建了对象?我的意思是如果我将它传递给一个 php 页面,它会正确地 json_decode 吗?
thanks
谢谢
回答by felixsigl
try find()
instead of first()
:
尝试find()
代替first()
:
links[index] = $(this).find('a').attr('href');
回答by VMOrtega
Try this:
尝试这个:
$('#myfavorites p').each(function(key,value) {
links[key] = $(value).first('a').attr('href');
});
jquery each docs: http://api.jquery.com/jQuery.each/
jquery 每个文档:http: //api.jquery.com/jQuery.each/