2017-07-28 19 views
1

サイトが特定の幅(768)を超えている場合にロードする要素があり、サイズ変更時にデタッチして再度適用できる要素があります。しかし、私が切り離す前にサイズを変更すると、多くのエラーが発生します。 これは動作しますが、私はすでに取り外された項目がそこにいる、それが動作しなくなったかどうかを確認しようとするとエラー JQuery既にデタッチされている場合にのみアイテムを追加する

$(function(){ 
    var $window = $(window), 
     $html = $('html'), 
     $putter; 
function resize(){ 
    if ($window.width() < 769){ 
     $putter = $('.header_box').detach(); 
    } else if ($window.width() >= 769){ 
     $putter.appendTo('#nt_tool'); 
    } 

} 
$window 
    .resize(resize) 
    .trigger('resize'); 

}); 

をスローするコードがあります。それはまだ切り離されますが、もはや追加されません。

$(function(){ 
var $window = $(window), 
    $html = $('html'), 
    $putter; 
function resize(){ 
    if ($window.width() < 769){ 
     $putter = $('.header_box').detach(); 
    } else if (($window.width() >= 769) && ($putter !== null)){ 
     $putter.appendTo('#nt_tool'); 
    } 

} 
$window 
    .resize(resize) 
    .trigger('resize'); 

}); 

エラー

Uncaught TypeError: Cannot read property 'appendTo' of undefined 
+0

多分問題はである:(!$パター== null)の && ことができますが、エラーの過去? –

+0

取得しているエラーは何ですか? – lloyd

答えて

0

アイテムの移動を変数宣言に剥離することが問題を修正し、追記工程において記憶された変数をチェックする必要性を除去します。以下の機能コード。

$(function(){ 
var $window = $(window), 
    $html = $('html'), 
    $putter = $('.header_box'); 
function resize(){ 
    if ($window.width() < 769){ 
     $putter.detach(); 
    } else if ($window.width() >= 769){ 
     $putter.appendTo($('#nt_tool')); 
    } 
} 
$window 
    .resize(resize) 
    .trigger('resize'); 

});