Javascript:如何检查URL是否包含单词
我想检查浏览器中的URL是否包含单词“Desktop”(我从桌面启动html文件)。其url为:file:///C:/Users/Joe/Desktop/TestAlert.html" 但是应该会出现警报,但这不起作用 这是我的密码:Javascript:如何检查URL是否包含单词,javascript,Javascript,我想检查浏览器中的URL是否包含单词“Desktop”(我从桌面启动html文件)。其url为:file:///C:/Users/Joe/Desktop/TestAlert.html" 但是应该会出现警报,但这不起作用 这是我的密码: <html> <head> <script type="text/javascript"> $(document).ready(function () { if(window.location.href.contains
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.contains("Desktop") > -1) {
alert("Alert: Desktop!");
}
});
</script>
</head>
<body>
<h1>Test001</h1>
</body>
</html>
$(文档).ready(函数(){
if(window.location.href.contains(“桌面”)>-1){
警报(“警报:桌面!”);
}
});
Test001
我在Firefox、Chrome和Internet Explorer中测试了这一点。
如果有人能帮助我,那将是非常好的 改用
indexOf
console.log(window.location.href.indexOf("javascript"));
同样的规则也适用,任何>-1表示它已经找到了某种方法
您不需要DOM就可以了。您可以使用regexp
url = window.location.href;
if( url.match(/desktop/gi) ) {
alert("Alert: Desktop!");
}
使用此选项,您可以检查两个或多个单词,如“/desktop | home/gi”
$(文档).ready(函数(){
if(window.location.href.indexOf(“桌面”)>-1){
警报(“警报:桌面!”);
}
});
Test001
请尝试此方法,它将为您提供解决方案如果您想使用jQuery,您需要链接到其源代码。 另外,请使用
indexOf
而不是contains
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("Desktop") > -1) {
alert("Alert: Desktop!");
} else {
alert("window.location.href: " + window.location.href);
}
});
</script>
</head>
<body>
<h1>Test001</h1>
</body>
</html>
$(文档).ready(函数(){
if(window.location.href.indexOf(“桌面”)>-1){
警报(“警报:桌面!”);
}否则{
警报(“window.location.href:+window.location.href”);
}
});
Test001
提示:当您遇到Javascript问题时,在浏览器中按f12打开开发工具,然后按f5刷新页面。然后检查控制台选项卡上是否有错误消息,例如“未捕获引用错误:$未定义”,以及源选项卡上是否有红色下划线的代码部分。您是否在查找
查询字符串
参数或url
中的任何字符串?请使用indexOf而不是contains。谢谢您,这非常有用!“DOM准备好了吗?”这就是答案point@JoeSharePoint很高兴它有帮助,请投票并将其标记为正确答案。:)
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');
}
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("Desktop") > -1) {
alert("Alert: Desktop!");
} else {
alert("window.location.href: " + window.location.href);
}
});
</script>
</head>
<body>
<h1>Test001</h1>
</body>
</html>
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');
}