[英]Why doesn't Jquery let me do this
document.getElementById("main").src = '02.jpg';
works 作品
but 但
$('#main').src = '02.jpg';
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. $('#main')
返回一个jQuery对象,而不是HTMLElement,因此在jQuery对象上没有定义src
属性。 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). Mike展示了一种设置src
属性的方法(他展示的方法可能被认为是最类似于jQuery的方法)。 A couple of other ways 其他几种方式
$("#main")[0].src = '02.jpg';
or 要么
$("#main").get(0).src = '02.jpg';
$('#main').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. 从$(...)获得的jQuery包装器不会重现它包装的DOM对象的所有属性和方法。 You have to stick to jQuery-specific methods on the wrapper object: in this case attr
as detailed by Mike. 您必须在包装对象上坚持jQuery特定的方法:在这种情况下,请参见Mike详细介绍的attr
。
The 'prototype' library, in contrast to jQuery, augments existing DOM objects rather than wrapping them. 与jQuery相比,“原型”库增强了现有的DOM对象,而不是包装它们。 So you get the old methods and properties like .src
in addition to the new ones. 因此,除了新方法和属性之外,您还可以获得.src
类的旧方法和属性。 There are advantages and drawbacks to both approaches. 两种方法都有优点和缺点。
$("#main")
is a collection of matches from a search. $("#main")
是来自搜索的匹配项的集合。 document.getElementById("main")
is a single DOM element - that does have the src
property. document.getElementById("main")
是单个DOM元素-确实具有src
属性。 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)
. 如果要在$(x)
返回的集合中的所有元素上设置某些属性,请使用attr(x,y)
方法,即使该元素只是getElementById(x)
的单个元素。
It's akin to the difference between int
and int[]
- very different beasts! 这类似于int
和int[]
之间的区别-百兽完全不同!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.