将所有文本实例转换为链接(除非已包含在 中)
我想设置一些内容来查找所选单词的所有实例并将它们转换为同页链接,但任何已经是链接或以其他方式包含在锚标记中的内容除外。
例如:
makelinkfunction("text_string", "link")
会转换这个:
Here is a text_string to dynamically link.
This text_string links elsewhere. This text_string is within the default link destination.
进入这个:
Here is a text_string to dynamically link.
This text_string links elsewhere. This text_string is within the default link destination.
第一行上的“text_string”实例转换为链接,而另外两个已经包含在标记中的实例将保持不变。
编辑:这不是一个重复的问题。 我不只是在寻找一个脚本来将字符串的所有实例转换为链接。 我已经找到了几种可能的解决方案(我选择使用的是使用Ben Alman的jQuery replaceText插件,因为它function多样且易于使用,但我绝不会与之相关。)
正如我所说的,我需要能够为已经被标签包围的文本实例添加exception。
创建jQuery原型函数;
$.fn.makeLink = function(a, b) { //Setting function options... var options= { //Rename function arguments insideText: a, url: b, //Static html html: $(this).html(), //Already existing anchors existsAnchorRGX: new RegExp('.*?' + a + '.*?', 'gi'), existsAnchor: [], //insadeText RegExp insideTextRGX: new RegExp(a, 'gi'), insideTextAnchor: '' + a + '', //Temp already anchors temp: '', tempRGX: new RegExp('', 'gi'), //Output Html outputHtml: $(this).html() }; //loop already anchors and push while(alreadyAnchor = options.existsAnchorRGX.exec(options.html)) options.existsAnchor.push(alreadyAnchor[0]); //delete already anchors temporarily options.outputHtml = options.outputHtml.replace(options.existsAnchorRGX, options.temp); //replace not anchors string options.outputHtml = options.outputHtml.replace(options.insideTextRGX, options.insideTextAnchor); //replace temp to anchors while(options.tempRGX.exec(options.outputHtml)) { options.outputHtml = options.outputHtml.replace(options.temp, options.existsAnchor[0]); options.existsAnchor.shift(); } //write output html $(this).html(options.outputHtml); //Reset function options option = {}; };
并使用;
//$('p').makeLink('text_string', 'link'); $('body').makeLink('text_string', 'link');