javascript - JS :How to turn any value to be a hyperlink via HTML form

标签 javascript html url

我想将添加到表单的任何值转换为与标题链接(超链接)

例如:

:https://www.udemy.com/

结果(超链接):Udemy:在线类(class) - 按您的日程安排学习任何内容

这是我的代码

HTML

    <div class="container">
    <form action="" class="addform">
    <div class="input-group mb-3">
        <input type="url" class="form-control" id="item" aria-describedby="emailHelp" placeholder="Enter link">            <div class="input-group-append">
          <button class="btn btn-primary" id="addItem" type="button">Submit</button>
        </div>
      </div>
    </form>
  </div>

JS

document.getElementById('addItem').addEventListener('click', function() {

    var value = document.getElementById('item').value;

    if (value) addItemToList(value);
});


function addItemToList(text) {

var list = document.getElementById('linkss')
var item = document.createElement('li');
item.innerHTML = text;

var buttons = document.createElement('linkss');
buttons.classList.add('buttons')

var remove = document.createElement('button');
remove.classList.add('remove');
// remove.innerHTML = removeIcon;

var add = document.createElement('button');
add.classList.add('add');

// buttons.appendChild(remove);
item.appendChild(buttons);

list.appendChild(item);
}

enter image description here

最佳答案

🌈你需要做什么

为了做到这一点,您必须加载该页面并获取其 <title>元素。

❌从前端获取页面

您可以尝试以两种不同的方式做到这一点:

  • 使用 AJAX GET 请求获取页面内容,在这种情况下您将收到 CORS 错误:

    Failed to load https://www.udemy.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://stackoverflow.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

    fetch('https://www.udemy.com');

  • 使用 <iframe> ,在这种情况下您将得到 X-Frame-Options错误:

    Refused to display 'https://www.udemy.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

    <iframe src="https://udemy.com" />

🌎 使用 API

正确的方法是使用代理/API,它会为您发出相同的 GET 请求,获取页面标题并将其发回。例如:

  • Textance :一个简单的 API,仅检索页面标题。这只是一个示例,因为您还会得到 Access-Control-Allow-Origin如果您尝试在页面上使用它,则会出错。

    例如,https://textance.herokuapp.com/rest/title/http%3A%2F%2Fudemy.com返回文本:

    Online Courses - Learn Anything, On Your Schedule | Udemy
    
  • URL Meta :另一个返回附加元数据的 API,并且公开可用,因此您可以直接从应用程序使用此 API,但速度有点慢,有时可能会出现故障。

    例如,https://url-meta.herokuapp.com/?url=http%3A%2F%2Fwww.udemy.com返回以下 JSON 响应:

    {
      "result": {
        "status": "OK"
      },
      "meta": {
        "url": "http://udemy.com",
        "type": "text/html",
        "title": "Online Courses - Learn Anything, On Your Schedule | Udemy",
        "image": "https://www.udemy.com/staticx/udemy/images/v6/logo-coral.svg",
        "description": "Udemy is an online learning and teaching marketplace with over 65,000 courses and 15 million students. Learn programming, marketing, data science and more.",
        "favicon": "https://www.udemy.com/staticx/udemy/images/v6/favicon-128.png",
        "feed": {
          "link": "http://udemy.com/"
        }
      }
    }
    

✨ 工作示例

要使用它,只需使用您想要从中获取标题的 URL 发出 GET 请求即可。例如,使用 Fetch API ,IE 不支持:

const input = document.getElementById('input');
const list = document.getElementById('list');

document.getElementById('add').onclick = () => {
  let url = input.value;
  
  if (!url) return;
  
  if (url.indexOf('http') !== 0) {
    // Make sure the url we send always starts with http or https:
    url = `http://${ url }`;
  }
  
  // Clear input field:
  input.value = '';
  
  const li = document.createElement('li');
  
  // Create a new entry in the list indicating we are still loading the title:
  
  li.innerText = `Loading title for ${ url }...`;
  
  list.appendChild(li);
  
  // Request the actual title of that URL from the URL Meta API:
  
  fetch(`https://url-meta.herokuapp.com/?url=${ encodeURIComponent(url) }`)
    .then(res => res.json())
    .then(data => {
      // Once we get a response back, update the text/HTML inside the <li> we have just added
      // with the right text and <a> or an error message:
      
      if (data.result.status === 'ERROR') {
        li.innerText = `There was an error loading ${ url }: ${ data.result.reason }`;
      } else {
        li.innerHTML = `<a href="${ url }">${ data.meta.title }</a>`;
      }
    }).catch(() => {
      li.innerText = `There was an error loading ${ url }.`;
    });
};
body {
  margin: 0;
  font-family: monospace;
  line-height: 15px;
}

#menu {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  border-bottom: 3px solid #000;
  height: 33px;
}

#input,
#add {
  border: 0;
  outline: none;
  padding: 4px 8px;
  box-sizing: border-box;
  background: #FFF;
  font-family: monospace;
  text-align: left;
}

#input {
  width: 70%;
  border-right: 3px solid #000;
}

#add {
  width: 30%;
}

#input:hover,
#add:hover {
  background: #EEE;
}

#list {
  list-style: none;
  margin: 0;
  padding: 35px 0 0;
}

#list > li {
  border-bottom: 1px solid #000;
  padding: 10px;
}

#list > li > a {
  word-break: break-word;
  word-break: break-all;
}
<header id="menu">
  <input id="input" type="text" placeholder="URL" value="http://www.udemy.com" />
  <button id="add">ADD LINK</button>
</header>

<ul id="list"></ul>

🛠️ 构建您自己的 API/代理

或者,您可以实现自己的代理/API。这将是一个很好的起点:Getting the page title from a scraped webpage

关于javascript - JS :How to turn any value to be a hyperlink via HTML form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976284/

相关文章:

javascript - 从 url 字符串中删除文本 javascript

javascript - 如何在 Sublime 中不将 'do'/'package' 等对象键高亮为关键字?

javascript - document.getElementById ("").style.display ='none' ;不管用

javascript - 如何复制指针事件 :none in JavaScript 的行为

php - PHP、HTML 或 XML 中的 %S 是什么意思?

html - 如何在 div 元素内水平居中图像?

ios - 带有 URL 链接的图像

javascript - 如何将参数添加到 URL 并重新加载页面

php - 用 PHP 抓取一个网站,然后用 jQuery 遍历它

javascript - 使用 Angular 验证 Bootstrap 模式窗口按钮单击上的输入字段