美文网首页让前端飞
如果jquery找不到对象怎么检测?

如果jquery找不到对象怎么检测?

作者: acd8eef1b5d7 | 来源:发表于2018-06-26 17:33 被阅读31次

    应用场景:

    “灵感编程”网站的后台,在添加记录之后,body自动滚动从而定位到该行记录(方便继续添加);

    使用的代码:

    所在位置:

    D:\yfwww\kuihua\Application\Tpl\Houtai\Public\js\Common\init.js

    相关代码:

    $(function(){

    var last_top=300;

    // var last_top=1000;

    var gundong_top=0;

    // 需要移动的距离

    var obj=$('.table tr[class=current_item]');

    console.log(obj);

    // if (obj.length!=0) {

    // if (obj) {

    if (obj.offset().top) {

    // if (obj != undefined) {

    var self_top=obj.offset().top;

    // console.log('self_top='+self_top);

    if (self_top>last_top) {

    gundong_top=self_top-last_top;

    }

    $('html,body').animate({

    scrollTop: gundong_top,

    }, 400,"swing",function (){

    });

    }

    });

    使用其他方式,均提示这样的错误:

    解决方案:

    从上面console.log()中可以看到,如果没找到,这length为0,所以要使用length是否为0的检测方式才可以正确:

    即:最后正确的代码为:

    $(function(){

    var last_top=300;

    var gundong_top=0;

    // 需要移动的距离

    var obj=$('.table tr[class=current_item]');

    if (obj.length!=0) {

    var self_top=obj.offset().top;

    if (self_top>last_top) {

    gundong_top=self_top-last_top;

    }

    $('html,body').animate({

    scrollTop: gundong_top,

    }, 400,"swing",function (){

    });

    }

    });

    成功执行后,可以正确定位,如图:

    本文代码查询:

    详细查看地址:

    http://www.phpkhbd.com/note/121/2875

    相关文章

      网友评论

        本文标题:如果jquery找不到对象怎么检测?

        本文链接:https://www.haomeiwen.com/subject/vrmmyftx.html