我怎么能这样做呢:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
我怎么能这样做呢:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.contains("franky")) // This doesn't work, any suggestions?
{
alert("your url contains the name franky");
}
});
</script>
当前回答
regex方式:
var matches = !!location.href.match(/franky/); //a boolean value now
或者在一个简单的陈述句中你可以用:
if (location.href.match(/franky/)) {
我用这个测试网站是在本地运行还是在服务器上运行:
location.href.match(/(192.168|localhost).*:1337/)
它检查href是否包含192.168或localhost AND,后面跟着:1337。
如您所见,当条件变得有点棘手时,使用regex比其他解决方案更有优势。
其他回答
放入你的js文件
var url = window.location.href;
console.log(url);
console.log(~url.indexOf("#product-consulation"));
if (~url.indexOf("#product-consulation")) {
console.log('YES');
// $('html, body').animate({
// scrollTop: $('#header').offset().top - 80
// }, 1000);
} else {
console.log('NOPE');
}
if (window.location.href.indexOf("franky") != -1)
会这么做的。或者,你可以使用regexp:
if (/franky/.test(window.location.href))
尝试indexOf
if (foo.indexOf("franky") >= 0)
{
...
}
您也可以尝试搜索(正则表达式)
if (foo.search("franky") >= 0)
{
...
}
试试这个,它更短,工作完全像window.location.href:
if (document.URL.indexOf("franky") > -1) { ... }
如果你想检查之前的URL:
if (document.referrer.indexOf("franky") > -1) { ... }
窗口。location不是String,但它有toString()方法。所以你可以这样做:
(''+window.location).includes("franky")
or
window.location.toString().includes("franky")
从旧的Mozilla文档:
位置对象有一个toString 方法返回当前URL。你 也可以将字符串赋值给 window.location。这意味着你 可与窗口工作。位置就好像它 在大多数情况下都是字符串。 有时候,比如当你需要的时候 调用一个String方法,你 必须显式调用toString。