简体   繁体   English

为什么此代码段无效?

[英]Why this snippet isn't working?

Can anyone help me find what is wrong with my small snippet? 谁能帮助我找出我的小片段的毛病?

$(window).on("load resize", function() {
   if ($(window).width() < 770) {
      $(".side-by-side.right div").each(function() {
          $(this).insertAfter($(this).parent().find('img'));
      });
   } else {
      $(this).insertBefore($(this).parent().find('img'));
   }
});

The first command just above the else works, but what after the else dose not, what am I doing wrong? 在else之上的第一个命令有效,但是在else不起作用之后,我在做什么错呢? I am positive it is something tiny like the place of } or ) or maybe forgot to add ; 我肯定这是}或)之类的小事,或可能忘记加; somewhere! 某处!

http://jsfiddle.net/fD265/ http://jsfiddle.net/fD265/

In the else statement, you're trying to reference the parent of the window object. 在else语句中,您尝试引用window对象的父对象。 That's why it's not doing anything--there is no parent of the window object. 这就是为什么它什么都不做的原因-窗口对象没有父对象。

The first part (if) works, because in that .each() $(this) will refer to your div elements. 第一部分(if)有效,因为.each()$(this)将引用您的div元素。 The $(this) in the else is still referring to window. else中的$(this)仍指window。

Fixing it will depend on what you're trying to do--which I can't really tell. 修复它取决于您要尝试执行的操作-我真的无法告诉您。 But, that's at least why it's not working. 但是,至少这就是为什么它不起作用的原因。 :-) :-)

Since it's not clear, what you are trying to achieve, this may be, what you are looking for? 由于不清楚,您正在尝试实现什么,这可能是您正在寻找什么?

$(window).on("load resize", function() {
    if ($(window).width() < 770) {
        $(".side-by-side.right div").each(function() {
            $(this).insertAfter($(this).parent().find('img'));
        });
    } else {
        $(".side-by-side.right div").each(function() {
            $(this).insertBefore($(this).parent().find('img'));
        });
    }
});

In the else block, this references window instead of the object, you want to edit. 在else块中, this参考窗口代替您要编辑的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM