Consider the following 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.
$('#saveFav').click(function() {
var toSave = { "searchtext" : $('#searchText').val().trim() };
var links = {};
$('#myfavorites p').each(function(index) {
links[index] = $(this).first('a').attr('href');
})开发者_JAVA百科;
toSave.links = links;
}
But in $('#myfavorites p').each function, $(this) isn't the p element. I am missing something here. How can I iterate in all p and find the first a element?
And am I construction the object correctly? I mean if I pass it to a php page, will it json_decode correctly?
thanks
try find()
instead of first()
:
links[index] = $(this).find('a').attr('href');
first has no selector parameter
Try this:
$('#myfavorites p').each(function(key,value) {
links[key] = $(value).first('a').attr('href');
});
jquery each docs: http://api.jquery.com/jQuery.each/
.first()
does not work that way. It takes a selector and returns the 1st from the list, and takes no arguments.
$('a', this).first().attr('href');
Or you can use the :first
selector.
$('a:first', this).attr('href');
精彩评论