【发布时间】:2014-02-10 09:06:20
【问题描述】:
我正在用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 或任何其他解决方案中生成此基本 URL 的任何帮助,谢谢 :)
我更喜欢仅使用 Javascript 的解决方案,因为我使用的是 CodeIgniter,所以 document.base_url 变量与从 protocol 到 index.php 的 URL 段看起来很方便
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 the path to the segment
return window.location.origin + pathArray.slice(0,indexOfSegment).join('/') + '/';
}
【问题讨论】:
-
我使用的是相同的东西,但我使用隐藏的只读字段来存储 base_url() 因为我在类名中传递它时遇到了一些问题。
-
我不明白你为什么要添加一个带有
base_url的类,你可以阅读这篇文章来了解如何在js中获取base_url stackoverflow.com/questions/1420881/…
标签: javascript php html css codeigniter