如果URL包含特定字符串,那么运行jQuery函数?

4

如果我的URL包含单词“test”,我希望在我的网站上运行jQuery函数。

我要做的就是,如果我的URL包含“rest”字符串,则在页面上的元素中添加一个边距?

我已经添加了一个jsfiddle来展示我目前所做的。

$(document).ready(function(){         
    // How can I check to see if my url contains the word 'TEST' then run the below function?
    $('.block-widget').css('margin-top, 252px')     
});
6个回答

9

使用 window.location 获取当前位置的URL。

根据条件,您可以应用margin-top属性。

$(document).ready(function(){         
     var pathname = window.location.pathname;
     if(pathname.indexOf('text') > -1){
        $('.block-widget').css('margin-top, 252px');
     }     
});

1
我认为路径不是“test”应该出现的唯一部分。 - Bergi
@Bergi 我们会假设 OP 对编程有足够的了解,可以自己检查 window.location 并找到解决方案。 :D - omninonsense

2
$(document).ready(function(){         
   if (document.url.match(/test/g)){
     $('.block-widget').css('margin-top, 252px')     
  }
});

0

name*='keyword'选择器是一个真正的选项。

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>

资源:https://api.jquery.com/attribute-contains-selector/


0

0

试一下这个

$(document).ready(function(){         
    var patt=/test/g;
    if(patt.test(window.location.pathname)){
    $('.block-widget').css('margin-top, 252px')  
  }   

});

0
获取路径名: < p > < code > var pathname = window.location.pathname;

然后检查它是否包含“TEST”。 < p > < code > if (pathname.toLowerCase().indexOf("test") >= 0)


你正在使用 toLowerCase(),因此你应该检查是否为 'test'。 - Steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接