例如,当单击ahref时,我想转到stackoverflow.com。用户输入URL,因此它可以在开头添加https://。只要URL的开头确实有https://,URL便可以正常工作并链接到页面,但是没有URL时。它保留文件路径,例如:file:/// C:/Users/..../stackoverflow.com
我该如何解决? https://codepen.io/anon/pen/rKZGdG
let results = document.getElementById('results');
// let url = "https://www.facebook.com"; WORKS
let name = "result";
let url = "facebook.com";
// this one leaves on the webite when Visit is clicked eg. file:///C:/User/../facebook.com
//I want the user to be able use to fb.com or http://www.fb.com, how can I do this?
results.innerHTML += '<div class="card bg-light p-3">'+
'<h3>'+name+
' <a class="btn btn-secondary" target="_blank" href="'+url+'">Visit</a> ' +
' <a onclick="delete(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</h3>'
+ '</div>';
<div id="results">
</div>
答案 0 :(得分:0)
只需在您的网址前添加//。因此,在您的情况下,这应该可行:
results.innerHTML += '<div class="card bg-light p-3">'+
'<h3>'+name+
' <a class="btn btn-secondary" target="_blank" href="//'+url+'">Visit</a> ' +
' <a onclick="delete(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</h3>'
+ '</div>';
这是因为当您添加没有协议或斜杠的链接时,它会被解释为相对路径。