use*_*837 2 javascript php jquery backbone.js
任何人都可以帮助我如何删除或替换JS模板中的现有链接.我使用backbone.js.
这是我的代码:
<script id="option-show-template" type="text/template">
<address>
<abbr title="Website">Web :</abbr> <%= (website)? '<a href="'+ website +'" id="website">' + website + '</a>' : '' %></address>
</script>
Run Code Online (Sandbox Code Playgroud)
输出:
Web: www.test.com
Run Code Online (Sandbox Code Playgroud)
问题是即使它会输出正确的数据,但href attr并不完全显示正确的数据.我的localhost/testserver包含在href属性中.
Web: <a href="localhost/testserver/www.test.com">www.test.com</a>
Run Code Online (Sandbox Code Playgroud)
我想要的是删除默认的基本网址.必须像这样输出:
Web: <a href="www.test.com">www.test.com</a>
Run Code Online (Sandbox Code Playgroud)
加 http://
试试这个
<abbr title="Website">Web :</abbr> <%= (website)? '<a href="http://'+ website +'" id="website">' + website + '</a>' : '' %></address>
Run Code Online (Sandbox Code Playgroud)
这有什么不对?
实现的问题是,当您设置href没有任何协议的属性(http,https,ftp等)时,浏览器会将链接视为相对路径.因此,当您在页面上查看页面时http://localhost/testserver/,您的页面就成了localhost/testserver/www.test.com
怎么修??
简而言之,要解决问题,您需要http://在网址前添加,如果没有.您可以通过多种方式实现这一目标,例如:
http://使用jquery 替换所有url prepend选项1或2很容易实现并且可以解决您的问题,如果您确定您URLs将始终像您的示例.但是对于以下用例会失败:
http://google.com).然后你的网址就会变成http://http://google.com my/relative/url).然后它应该保持不变,但你会得到无域名的无效网址 - http://my/relative/url终极解决方案!!
因此,您可以使用以下功能来修复您的URL
//Check if it is a valid URL with FQDN
function isValidUrl(url) {
return url.match(/((ftp|http|https):\/\/)?[\w\-]+\.[\w\-]+/);
}
//Check if the url already contain a protocol or not
function hasProtocol(url){
return url.match(/(ftp|http|https):\/\//);
}
//Fix your URL only if needed!!
function setHttp(link) {
return (!isValidUrl(link) || hasProtocol(link)) ? link : 'http://' + link;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式使用此功能来解决问题.您可以在此处找到示例实现
快乐的编码!!