jQuery target $(window) on a specific webpage



我只是想知道是否有什么简单的方法可以让$(window(只在localhost/website/hello上工作,而不是在localhost/wwebsite/bye 上工作

我做了一个简单的测试脚本,

$(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height()){
        alert('Hello World');
    }
});

问题是,这个片段将适用于加载脚本的所有页面。。。

使用location.href值检查正在加载的页面。

if (location.href == "your_page") {
    $(window).scroll(function(){
        if ($(window).scrollTop() == $(document).height() - $(window).height()){
            alert('Hello World');
        }
    });
}

若要匹配一组不同的页面,请使用正则表达式。

实时演示

var currentPage = window.location.href.match(/website/(.*)/)[1];
if(currentPage === 'hello/'){
    $(window).scroll(function(){
        if ($(window).scrollTop() == $(document).height() - $(window).height()){
            alert('Hello World');
        }
    });
}

所以基本上CCD_ 2之后的任何东西都将被匹配。

首先检查页面路径名称,然后应用条件

var url = location.pathname;

if ("url:contains('localhost/website/hello')") {
    if ($(window).scrollTop() == $(document).height() - $(window).height()){
        alert('Hello World');
    }
  }

  else ("url:contains('localhost/website/bye')") {
    //do something else
  }
if( window.location.hostname.indexOf("localhost") != -1 ) {
  alert('on localhost'); 
}
if( window.location.pathname.indexOf("hello") != -1 ) {
 alert('path contains "hello"');  
}

您可以使用window.location对象来解析url并检查特定部分。

最新更新