开发者

Why doesn't Jquery let me do this

开发者 https://www.devze.com 2022-12-08 16:15 出处:网络
document.getElementById(\"main\").src = \'02.jpg\'; works but $(\'#main\').src = \'02.j开发者_JS百科pg\';
document.getElementById("main").src = '02.jpg';

works

but

$('#main').src = '02.j开发者_JS百科pg';

doesn't


$("#main").attr("src", "02.jpg");


$('#main') returns a jQuery object, not a HTMLElement, therefore no src property is defined on the jQuery object. You may find this article useful.

Mike has shown one way of setting the src attribute (the way he has shown could probably be considered the most jQuery like way of doing it). A couple of other ways

$("#main")[0].src = '02.jpg';

or

$("#main").get(0).src = '02.jpg';


$('#main').src = '02.jpg';

The jQuery wrapper you get from $(...) does not reproduce all properties and methods of the DOM object(s) it wraps. You have to stick to jQuery-specific methods on the wrapper object: in this case attr as detailed by Mike.

The ‘prototype’ library, in contrast to jQuery, augments existing DOM objects rather than wrapping them. So you get the old methods and properties like .src in addition to the new ones. There are advantages and drawbacks to both approaches.


$("#main") is a collection of matches from a search. document.getElementById("main") is a single DOM element - that does have the src property. Use the attr(x,y) method for when you want to set some attribute on all of the elements in the collection that gets returned by $(x), even if that is only a single element as in getElementById(x).

It's akin to the difference between int and int[] - very different beasts!

0

精彩评论

暂无评论...
验证码 换一张
取 消