使链接点击Javascript? [英] Making links clickable in Javascript?

查看:150
本文介绍了使链接点击Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个简单的方法将字符串从

 然后转到http:/example.com/和foo酒吧! 

转换为

 然后转到< a href =http://example.com> example.com< / a>和foo吧! 

在现有的HTML页面中的Javascript中

解决方案

是的。最简单的方法是使用正则表达式来替换链接等价物的链接。例如:

  node.innerHTML = node.innerHTML.replace(/(http:\ / \ / / ^ $ s 






$ $ $

(我的正则表达式有点生疏,所以你可能需要使用语法)。这只是一个简单的例子。这里需要注意脚本注入(例如,如果我有 http://>< script> doevil()< / script> )。方法来解决这个问题是通过使用链接构建函数:

$ $ p $ node.innerHTML = node.innerHTML.replace(/ .. 。/ g,buildLink($ 1));

其中 buildLink()可以检查以确保URL不包含任何恶意内容。



然而,RegEx-innerHTML方法在大型机构上表现不佳因为它撕掉并重建了整个节点的HTML内容,你也可以通过DOM方法来实现:


  • 查找对文本节点的引用
  • 在内容中,查找URL的开始和结束索引

  • 使用 splitText() 方法将节点拆分为3:before,link,after

  • 创建< a> href 与链接相同

  • < a>
    节点
  • 使用 appendChild()将链接移至< a> 节点


Is there an simple way of turning a string from

Then go to http:/example.com/ and foo the bar!

into

Then go to <a href="http://example.com">example.com</a> and foo the bar!

in Javascript within an existing HTML page?

解决方案

Yes. The simplest way is to use a regular expressions to substitute things that look like a link for their linked equivalents. Something like:

node.innerHTML = node.innerHTML.replace(/(http:\/\/[^\s]+)/g, "<a href='$1'>$1</a>")

(my RegEx is a little rusty, so you may need to play with the syntax). This is just a simple case. You need to be wary of script injection here (for example if I have http://"><script>doevil()</script>). One way to work around this is by using a link building function:

node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1));

Where buildLink() can check to make sure the URL doesn't contain anything malicious.

However, the RegEx-innerHTML method will not perform very well on large bodies of text though, since it tears down and rebuilds the entire HTML content of the node. You can achieve this with DOM methods as well:

  • Find reference to the text node
  • In the content, find start and end indexes of a URL
  • Use splitText() method to split the node into 3: before, link, after
  • Create an <a> node with the href that's the same as the link
  • Use insertBefore() to insert this <a> node before the link
  • Use appendChild() to move the link into the <a> node

这篇关于使链接点击Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆