带有斜杠(/)的URL无法在浏览器中正确呈现

时间:2012-06-07 19:32:04

标签: jquery url browser

这可能是太多的信息,但在这里你去...用户输入一个网址,网址通过ajax发送到后端,以确认它存在。如果是,则返回url和contentType(text / html,image / jpeg ...等)。下面的代码是ajax成功回调。

var template = 
"<span class='urlFile'>"+data.contentType+'</span>'+
"<span class='urlPath' title="+data.url+'>'+data.url+'</span>';

$(template).prependTo(fieldWrapper);

问题是生成的html呈现部分乱序。以下是Firebug(Chrome)的输出补充。请注意,data.url(http://api.jquery.com/appendto/)未包含在span.urlPath中。

<span class="urlFile">html</span>
<span class="urlPath" title="http://api.jquery.com/appendto"></span>
http://api.jquery.com/appendto/

此外,当我添加alert(template)时,我得到:

<span class='urlFile'>html</span>
<span class='urlPath' title=http://api.jquery.com/prependto/>http://api.jquery.com/prependto/</span>

......这是正确的。我认为问题与浏览器呈现尾随/有关;但是,除了删除斜杠之外,我不确定如何修复它。

仅供参考:删除尾部斜线似乎可以解决问题,即:

var url = data.url.replace(/\/$/,'');

......但它真的需要吗?听起来这是一个坏主意:

Is it always safe to remove a trailing slash from a URL?

1 个答案:

答案 0 :(得分:1)

你对尾随斜线是正确的。浏览器认为您正在关闭第二个span元素。要解决此问题,请将title属性放在引号中,如下所示:

var template = 
"<span class='urlFile'>"+data.contentType+'</span>'+
"<span class='urlPath' title='"+data.url+"'>"+data.url+'</span>';

$(template).prependTo(fieldWrapper);​