我怎么能这样做呢:
<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>
当前回答
尝试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) { ... }
你可以像这样使用indexOf:
if(window.location.href.indexOf("franky") != -1){....}
还要注意字符串的href,否则你会这样做:
if(window.location.toString().indexOf("franky") != -1){....}
放入你的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');
}
变得更容易
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.href;
if(url.includes('franky')) //includes() method determines whether a string contains specified string.
{
alert("url contains franky");
}
});
</script>
相反,我喜欢这种方法。
top.location.pathname.includes('franky')
它在很多情况下都有效。