What's wrong with my code [closed]
This is the first thing I write in javascript, so I hope its a basic error
What I'm trying to achieve here: Take a bunch of links from a page, load their contents query for links inside and add them to a list on current page.
I get error on the append And in JQ documentation they say the method can get a JQ object
<script type="text/javascript">
$(document).ready(function () {
var wtf = $(".download");
var links = $("a", wtf)
links.each(function (index) {
var newFrame = document.createElement("div");
$(newFrame).load($(this).context.href, function (response, status, xhr) {
if (status == "error") {
alert("error");
开发者_如何学Go }
$("a", response).each(function (index) {
$("#results").append($(this));
});
});
// $("#results").append(newFrame);
});
});
</script>
Let's see if my guessing error checking abilities are good enough for this:
// No point really in using context here.
// This would be better, or at least more readable
var links = $(".download a");
// No need to add in the argument if you're not actually going to use it
links.each(function() {
// Doing this will get you create the jQuery object
// without having to use the DOM createElement method
var newFrame = $('<div />');
// this.href is shorter and neater
newFrame.load(this.href, {
'html': '.ajax'
}, function(response, status, xhr) {
if (status == "error") {
console.log(xhr);
}
// This is the odd part - response is a selector?
// This should loop through each anchor that are a child
// Of the element selected by the response receieved
// Using appendTo here is better than looping through
// each element and using .append() there
$(response).find("a").appendTo("#results");
// And finally of course because this is .load()
// Remember that the actual response is also
// appeneded to the element in question,
// hence the extra .ajax appearing there
});
// This occures outside of callback,
// so it's actually executed *before* the code above
$("#results").append(newFrame);
});
See jsfiddle for this piece of code actually working: http://jsfiddle.net/E589q/4/
the load function does not have error handling capabilities, it is meant for simple Ajax functionality only.
Try this
<script type="text/javascript">
<!--
$(document).ready(
function () {
var links = $("a.download")
$.each(links,
function () {
var url = $(this).attr('href');
var newFrame = $("<div></div>").appendTo('body').css({position: 'absolute', top: '100px', left: '100px'});
$(newFrame).load(url)
})
})
//-->
</script>
精彩评论