jQuery - getting attribute from HTML Text - IE not working
I'm using and $.ajax method to get an html text. I would like to parse this html, getting the "src" from an "img" tag. I've done this way:
$.ajax({
type: "GET",
url: "image1.html",
success: function(msg){
var htmlCode = $(msg).html();
开发者_如何转开发 var title = $("#immagine", htmlCode).attr("src");
alert( title);
}
});
I can get the right result from Firefox and Chrome. They alert the correct "src" value (ex: 'pics/image.jpg'). But IE return an "undefined" alert. Can someone help me? Thanks
I don't really know why that works in any browser, the context should be an element, a document or a jQuery object, not a string.
Use the jQuery object as context instead of getting the html code from it:
var code = $(msg);
var title = $("#immagine", code).attr("src");
alert( title);
In your code:
var htmlCode = $(msg).html();
var title = $("#immagine", htmlCode).attr("src");
The first line wraps the response in a jQuery object, but then uses html()
to return the same HTML that the message was in the first place. Then, you wrap the source again.
You should use:
$(msg).find("#immagine").attr("src");
... to get the src
精彩评论