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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:57:09  来源:igfitidea点击:

Jquery selector .each()

jquery

提问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');

first has no selector parameter

第一个没有选择器参数

回答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/

回答by Rocket Hazmat

.first()does not work that way. It takes a selector and returns the 1st from the list, and takes no arguments.

.first()不能那样工作。它接受一个选择器并从列表中返回第一个,并且不接受任何参数。

$('a', this).first().attr('href');

Or you can use the :firstselector.

或者您可以使用:first选择器。

$('a:first', this).attr('href');