请考虑以下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>
Run Code Online (Sandbox Code Playgroud)
按下按钮时,我想用所有链接创建一个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;
}
Run Code Online (Sandbox Code Playgroud)
但是在$('#myfavorites p')中.每个函数,$(this)都不是p元素.我在这里遗漏了一些东西.如何迭代所有p并找到第一个元素?
我是否正确构建了对象?我的意思是,如果我将它传递给php页面,它会正确地json_decode吗?
谢谢
fel*_*igl 10
尝试find()而不是first():
links[index] = $(this).find('a').attr('href');
Run Code Online (Sandbox Code Playgroud)