小编Neh*_*era的帖子

如何在javascript中获取基本URL

我正在使用CodeIgniter构建一个网站,我有各种资源,我使用base_url帮助函数加载,就像这样

<link rel="stylesheet" type="text/css" href="'.base_url('assets/css/themes/default.css').'" id="style_color"/>

生产(即www.mysite.com)

<link rel="stylesheet" type="text/css" href="http://www.mysite.com/assets/css/themes/default.css" id="style_color"/>

然后,我可以在这样的javascript中将此资源与另一个交换

$('#style_color').attr("href", "assets/css/themes/" + color_ + ".css");

会发生什么事情,它会尝试加载资源而不使用php生成的绝对路径,所以我的解决方案是在每个页面添加一个虚拟标签,像这样的PHP

<div id="base_url" class="'.base_url().'"></div>

然后我修改了javascript行

$('#style_color').attr("href", $('#base_url').attr("class") + "assets/css/themes/" + color_ + ".css");

它确实有效,但它看起来并不优雅,所以,我将不胜感激如何在javascript或任何其他解决方案中生成这个基本网址,谢谢:)


我更喜欢仅使用Javascript的解决方案,因为我使用的是CodeIgniter,一个document.base_url带有url段的变量protocol从而index.php显得很方便

document.base_url = base_url('index.php');

功能base_url()正在

function base_url(segment){
   // get the segments
   pathArray = window.location.pathname.split( '/' );
   // find where the segment is located
   indexOfSegment = pathArray.indexOf(segment);
   // make base_url be the origin plus …
Run Code Online (Sandbox Code Playgroud)

html javascript css php codeigniter

42
推荐指数
5
解决办法
15万
查看次数

标签 统计

codeigniter ×1

css ×1

html ×1

javascript ×1

php ×1