Home >Backend Development >PHP Tutorial >javascript - How to avoid a certain element not existing in html, causing js to obtain the attribute information of the element and report an error

javascript - How to avoid a certain element not existing in html, causing js to obtain the attribute information of the element and report an error

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-09-09 08:28:001288browse

The page code is as follows:

<code><empty name="search_data">
    <div class="box">
        <!-- html代码 -->
    </div>
</empty>

<script>
    var top = $('.box').offset().top;
    $("html,body").scrollTop(top);
</script></code>

As above, is a thinkphp syntax tag, which means that when "search_data" does not exist, the div element with class box will be output to the page. On the contrary, if the "search_data" data exists, the page will not have the div box. , in this case, how to avoid js error?

Reply content:

The page code is as follows:

<code><empty name="search_data">
    <div class="box">
        <!-- html代码 -->
    </div>
</empty>

<script>
    var top = $('.box').offset().top;
    $("html,body").scrollTop(top);
</script></code>

As above, is a thinkphp syntax tag, which means that when "search_data" does not exist, the div element with class box will be output to the page. On the contrary, if the "search_data" data exists, the page will not have the div box. , in this case, how to avoid js error?

<code>if($('[name="search_data]"').size()>0){
    //当“search_data”数据存在
}else{
    //当“search_data”不存在时
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn