2017-07-28 50 views
1

所以我有一個元素,在只有當該網站是有一定寬度(768)以上,我可以得到它的分離和reappend上調整大小的負荷。但是,如果在分離之前調整大小,它會引發很多錯誤。 這是工作,但是當我嘗試檢查已經分離項目在那裏它停止工作中引發錯誤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'); 

});