0

我想根据您所在的网址更改 div 的 css。

这是我想出的代码...

<script>
if (window.location.href == "http://www.example.com/?tab-1") {
    function(){ 
        $('body').css('color','red !important');
    }
}
</script>

有人可以解释如何根据当前 url 正确执行一个函数吗?

谢谢你。

4

3 回答 3

0

要根据 url 上问号后面的内容执行不同的功能(以面值表示问题),您可以使用以下命令:

var functions = {
    "tab-1": function() {
        //do tab-1 stuff
    },

    "tab-2": function() {
        //do tab-2 stuff
    }
}

$(function() {
    var qs = location.search;
    if (qs.length > 0) {
        var func = functions[qs.substring(1)]
        if ($.isFunction(func)) func();
    }
});
于 2013-09-09T23:47:44.757 回答
0
$(function(){

    var tab = window.location.href.split('?')[1]; // tab-1
    if(tab){
      $('body').addClass( tab );
    }

});

比在你的CSS中:

.tab-1{
   background: red ;  /* add !important if needed */
}
.tab-2{
   background: blue ; /* add !important if needed */
}

演示概念

于 2013-09-09T23:41:15.037 回答
-1

您应该调用window.onload以便在输入时捕获 url 并立即触发您想要的操作(在本例中为 css 更改)。

function changecss() {
    if (window.location.href == "http://www.example.com/?tab-1") {
        function(){ 
            $('body').css('color','red !important');
        }
    }

}

window.onload = changecss;
于 2013-09-09T23:38:30.883 回答