我有这个jQuery:
jQuery(".storyImg").each(
function(){
if(this.width() > this.height()){
jQuery(this).addClass("landscape");
} else if (this.width() < this.height()){
jQuery(this).addClass("portrait");
} else {
}
}
);
它似乎不起作用。我甚至无法从函数内部发出警报。它肯定包含在html文件中,而类.storyImg绝对是正确的。
答案 0 :(得分:1)
内部each
回调this
是指没有width
或height
方法的dom元素,您需要在jQuery包装器中调用这些方法元件
jQuery(".storyImg").each(function () {
var $this = jQuery(this)
if ($this.width() > $this.height()) {
$this.addClass("landscape");
} else if ($this.width() < $this.height()) {
$this.addClass("portrait");
} else {
}
});
答案 1 :(得分:0)
您需要执行jQuery(this).width()
和jQuery(this).height()
,因为this
不是jQuery对象。您的控制台应该有错误。您只需要在this
上调用jQuery一次。
您还应该等待$(window).load()
中的此操作,因为您要等待图片加载。
jQuery(".storyImg").each(function(){
var $this = jQuery(this);
if($this.width() > $this.height()){
$this.addClass("landscape");
} else if ($this.width() < $this.height()){
$this.addClass("portrait");
} else {
}
});
答案 2 :(得分:0)
没有js guru但是你不能打电话给this.width()
。就像你已经在那里使用jQuery(this).width()
一样。最好还是将它添加到var:
var $this = jQuery(this);
if($this.width() > $this.height()){
// blah
}