Retrieving links using Jquery
I posted this up a day or two ago, received an answer which worked on JSfiddle, but didn't work on my actual code.
<div id="PublicResults">
<h2>
<dl>
<dt>
<a onmouseout="swho.alone.OnMouseOut(event)" onmouseover="swho.alone.showPopup(event, 'DR647E481', 'pra**', '', '', '开发者_StackOverfloweveryone', 'closed')" href="/SWApp/detailAction.do?key=DR647E481&search=pra**&soundex=&stanfordonly=&affilfilter=everyone&filters=closed">Ajay Prakash</a>
</dt>
Now, I tried $jq("#PublicResults a").attr("href"), which worked in jsfiddle, but isn't working on the page (my console reads undefined). However, when I try $jq("#PublicResults a[href]").attr("href"), I get the url of the current webpage- so I guess the issue is that .attr() is returning only the first element
So my question is twofold- if what I wrote just above is correct, how do I make .attr() return all elements. If not, what should I do to retrieve the url in href?
You have to loop troughout the array list of all links do you want to scraping:
$jq("#PublicResults a").each(function()
{
alert($(this).attr("href"));
});
If you have your jQuery instance tied to $jq()
(instead of the usual $()
or jQuery()
), then $jq("#PublicResults a[href]").attr("href")
should work. Could you post a link to where it doesn't work?
I suspect one of the following:
- You may be running the jQuery code before the
#PublicResults
element is added to the page - It is possible that the
$jq()
function is not available - Something else may be altering your link href
You can use map to extract all of the href's from the jQuery wrapped objects. eg.
$('...').map(function() { return $(this).attr('href'); });
This returns a jQuery wrapped array, to get a normal JavaScript one, just use .get()
.
精彩评论