JQuery只有在已经分离的情况下才附加项目

时间:2017-07-28 20:28:07

标签: jquery

所以我有一个只在网站超过一定宽度(768)时加载的元素,我可以让它分离并重新调整大小。但是如果我在分离之前调整大小,它会引发很多错误。 这是可行的代码,但会抛出错误

$(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

1 个答案:

答案 0 :(得分: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');

});