【问题标题】:URL with trailing slash (/) is not rendering in browser properly带有斜杠 (/) 的 URL 未在浏览器中正确呈现
【发布时间】:2012-06-07 19:32:03
【问题描述】:

这可能是太多的信息,但你去吧......用户输入一个 url 并且 url 通过 ajax 发送到后端以确认它存在。如果是,它会返回 url 和 contentType(text/html、image/jpeg...ect)。下面的代码是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?

【问题讨论】:

    标签: jquery url browser


    【解决方案1】:

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

    var template = 
    "<span class='urlFile'>"+data.contentType+'</span>'+
    "<span class='urlPath' title='"+data.url+"'>"+data.url+'</span>';
    
    $(template).prependTo(fieldWrapper);​
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 2015-02-19
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多