我有以下代码,可从用户输入链接并使用anchor
href = link
标签
<html>
<head>
<title>Page Title</title>
<style>
#text-input {
border-left: 4px solid green;
text-indent: 12px;
}
</style>
</head>
<body>
<p>Enter a link</p>
<div id="text-input" contenteditable="true"></div>
<script>
let div = document.getElementById('text-input');
let anchor;
div.addEventListener('blur', event => {
let text = div.innerText;
div.innerText = '';
anchor = document.createElement('a');
div.appendChild(anchor);
anchor.innerText = text;
anchor.href = text;
// The below line logs the actual link of the anchor tag
console.log(anchor.href);
});
</script>
</body>
</html>
当我为href分配链接的值时,该链接似乎也包含一些默认的网站URL。我不想要这些默认网址。我该怎么办?
答案 0 :(得分:2)
也许这是相对网址的问题?如果没有,请在文本开头添加“ http://”。
答案 1 :(得分:2)
根据您的默认要求,您可以在输入数据后附加https或http。
anchor.innerText = text;
if(text.indexOf('http://')!=0 || text.indexOf('https://')!=0){
text = "http://"+text; //default http(or) https
}
anchor.href = text;
答案 2 :(得分:1)
您可能需要在开头添加http://或https://。
<html>
<head>
<title>Page Title</title>
<style>
#text-input {
border-left: 4px solid green;
text-indent: 12px;
}
</style>
</head>
<body>
<p>Enter a link</p>
<div id="text-input" contenteditable="true"></div>
<script>
let div = document.getElementById('text-input');
let anchor;
div.addEventListener('blur', event => {
let text = div.innerText;
div.innerText = '';
anchor = document.createElement('a');
div.appendChild(anchor);
anchor.innerText = text;
anchor.href = 'http://'+text;
// The below line logs the actual link of the anchor tag
console.log(anchor.href);
});
</script>
</body>
</html>