Traversing the result of $.get() with jQuery
I load some HTML via $.get(); I only want some parts of the result inserted into my html. So searched SO found this questions and then tried this:
$("a.load").cli开发者_高级运维ck(function() {
$.get(this.href, {}, function(result) {
content = $("#main", result);
console.log(content);
}, "html");
return false;
});
Though result
has the correct contents console.log(content)
returns []
. Anyone an idea what I'm doing wrong?
Thanks in advance!
If you're trying to do what it sounds like you are, .load() would be easier:
$("a.load").click(function() {
$("#WhereYouWantHTMLInjected").load(this.href + ' #main');
return false;
});
The line content = $("#main", result);
seems wrong. The second argument of a plain jQuery statement is scope -- you are giving it html and I suspect it doesn't know what to do with that. It gives back an empty jQuery array.
If you want to use jQuery to parse the resulting html, you have to add it to an element, then operate on it. So:
$("a.load").click(function() {
$.get(this.href, function(result) {
content = $("<div>").html(result);
// now content is a new jQuery element to do with as you please
// it's not in the DOM yet, mind you
var links = content.find("a"); // maybe you want the resulting links?
$("#main").append(links); // maybe you want to add them to the DOM?
}, "html");
return false;
});
The second parameter to a jQuery call has to be an element, a document or a jQuery-object. You are sending in a string, so it doesn't fit any set of valid parameters. I'm not sure how jQuery reacts to the invalid parameters, but I think that it simply ignores the string and looks for the selector in the current document instead.
Turn the string into elements by sending it to the jQuery function:
content = $("#main", $(result));
Note that it turns the string into elements by creating a div
element and set the string as innerHTML
, so the string has to be an HTML fragment, not a complete HTML document.
I recommend using .load() as Dave Ward mentioned.
If you were to use your own callback in $.get(), you'd need to do something like this (concept is straight out of jQuery source):
$("a.load").click(function() {
$.get(this.href, {}, function(result) {
var content = $("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(result.responseText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ""))
// Locate the specified elements
.find("#main").html();
console.log(content);
}, "html");
return false;
});
精彩评论