我怎么能这样做呢:
<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>
当前回答
可以使用javascript字符串方法进行匹配
Const url = window.location.href; Const find = 'questions'; Const found = url.match(find); console.log (url); If (found !== null && found[0] === find){ console.log('你在问题页面'); }其他{ console.log('您不在问题页面'); }
其他回答
放入你的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');
}
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比其他解决方案更有优势。
假设您有这个脚本
<div>
<p id="response"><p>
<script>
var query = document.location.href.substring(document.location.href.indexOf("?") + 1);
var text_input = query.split("&")[0].split("=")[1];
document.getElementById('response').innerHTML=text_input;
</script> </div>
url表单是www.localhost.com/web_form_response.html?text_input=stack&over=flow
写入<p id="response">的文本将被堆叠
你可以像这样使用indexOf:
if(window.location.href.indexOf("franky") != -1){....}
还要注意字符串的href,否则你会这样做:
if(window.location.toString().indexOf("franky") != -1){....}
变得更容易
<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>