最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to run a javascript function only on a certain page or pages? - Stack Overflow

programmeradmin2浏览0评论

I have the following function and I want to execute it only on specific pages in my Wordpress website. I tried with if (is_page('pagename') but I cannot get it to work. Any suggestions?

    $(function() {

        $('a[href*=\\#]:not([href=\\#])').click(function() {
            if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 2000);
                    return false;

                }

            }
        });

    });
}
})
;

I have the following function and I want to execute it only on specific pages in my Wordpress website. I tried with if (is_page('pagename') but I cannot get it to work. Any suggestions?

    $(function() {

        $('a[href*=\\#]:not([href=\\#])').click(function() {
            if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 2000);
                    return false;

                }

            }
        });

    });
}
})
;
Share Improve this question asked Jun 5, 2018 at 5:59 Roumen StratievRoumen Stratiev 111 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Something like this will work:

if (window.location.pathname=='/account') {

}

create a javascript file contained this script. then import the script to the pages those you want to execute this in that page by adding

<script src="URL/TO/YOUR/SCRIPT/nameOfScript.js"></script>

this into the end of the body part or to the header of the html

发布评论

评论列表(0)

  1. 暂无评论