jQuery在特定网页上定位$(窗口)

我只是想知道是否有任何简单的方法我可以定位$(窗口)只能在localhost / website / hello上工作而不是localhost / website / bye

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

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

问题是这个代码片段适用于加载脚本的所有页面…

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

 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 } 

使用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'); } }); } 

所以website/之后的任何东西都会匹配。

 if( window.location.hostname.indexOf("localhost") != -1 ) { alert('on localhost'); } if( window.location.pathname.indexOf("hello") != -1 ) { alert('path contains "hello"'); } 

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