我有一个网站,允许用户提交视频和属性来源,有时他们会链接到http://,有时只用www。进行链接。
由于各种原因,我需要在每个链接上添加http://以确保URL正确解析,因此我在运行页面时运行了一点jquery来检查链接。
$(document).ready(function(){
$('.status-contain a.source-container').each(function(){
this.href = this.href.replace('http://http//', 'http://');
});
});
当人们提交https://
的链接时,这就成了问题,因为附加的网址会变成http://https://
而jquery无法识别要更改的内容。
我应该创建某种if / function来检查URL是http还是https然后运行替换?
简单的问题,但我有点难过。
答案 0 :(得分:1)
也这样做,
this.href = this.href.replace('http://https//', 'https://');
您的代码变为,
$(document).ready(function(){
$('.status-contain a.source-container').each(function(){
this.href = this.href.replace('http://http//', 'http://');
this.href = this.href.replace('http://https//', 'https://');
});
});
答案 1 :(得分:0)
试试这个,检查https
中是否有href
,然后如下所示进行相应替换:
$(document).ready(function(){
$('.status-contain a.source-container').each(function(){
var hrefVal = this.href;
if(hrefVal.indexOf("https://")!=-1)
{
this.href = this.href.replace('http://https://', 'https://');
}
else
{
this.href = this.href.replace('http://http//', 'http://');
}
});
});
答案 2 :(得分:0)
您可以使用this plugin添加自定义网址方法验证。自定义验证器可以是这样的
jQuery.validator.addMethod("complete_url", function(val, elem) {
// if no url, don't do anything
if (val.length == 0) { return true; }
// if user has not entered http:// https:// or ftp:// assume they mean http://
if(!/^(https?|ftp):///i.test(val)) {
val = 'http://'+val; // set both the value
$(elem).val(val); // also update the form element
}
// now check if valid url
// http://docs.jquery.com/Plugins/Validation/Methods/url
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
return /^(https?|ftp)://(((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:)*@)?(((d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]).(d|[1-9]d|1dd|2[0-4]d|25[0-5]))|((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?)(:d*)?)(/((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)+(/(([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)*)*)?)?(?((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|[uE000-uF8FF]|/|?)*)?(#((([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(%[da-f]{2})|[!$&'()*+,;=]|:|@)|/|?)*)?$/i.test(val);
});