如何使用javascript用链接替换文本

How to replace text with links using javascript?

本文关键字:替换 文本 链接 何使用 javascript      更新时间:2023-09-26

这是我使用Jquery从html中取出文本的操作:

$(".text").each(function(){
        var texts = items[textCount]['data']['title'];
        $(this).text(texts);
         textCount = textCount + 1;
      });

我的问题,如果我想文本是一个url,那么它不会显示为链接,也是一个字符串添加到文本变量。我如何显示一个链接?如何将其作为参考添加到文本中?

输出应该像这样:

文本+ url

而非文本被链接为url: "<a href='""+link+"'">"+texts+"</a>"

您可以像这样为每个class=text的元素创建一个链接,它假设您有某种要用超链接包装的元素。我不能百分之百确定这就是你要找的。

$('.text').wrap('<a href="http://yourlinkhere.com"></a>');

像这样使用.attr()函数

$(this).attr("href", "your link");

但这只会工作,如果你有一个锚标记,如果没有,你可以创建一个锚标记在飞行

$(this).html("<a href='""+link+"'">"+texts+"</a>");

你可以这么做。注意:-这比attr()更有效,因为你直接处理对象属性。

this.href="yoururl"

你不需要通过下面的jquery代码调用在attr期间,为了仅仅设置href属性。

Jquery attr函数

attr: function( elem, name, value, pass ) {
        var nType = elem.nodeType;
        // don't get/set attributes on text, comment and attribute nodes
        if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
            return undefined;
        }
        if ( pass && name in jQuery.attrFn ) {
            return jQuery( elem )[ name ]( value );
        }
        // Fallback to prop when attributes are not supported
        if ( !("getAttribute" in elem) ) {
            return jQuery.prop( elem, name, value );
        }
        var ret, hooks,
            notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
        // Normalize the name if needed
        if ( notxml ) {
            name = jQuery.attrFix[ name ] || name;
            hooks = jQuery.attrHooks[ name ];
            if ( !hooks ) {
                // Use boolHook for boolean attributes
                if ( rboolean.test( name ) ) {
                    hooks = boolHook;
                // Use nodeHook if available( IE6/7 )
                } else if ( nodeHook ) {
                    hooks = nodeHook;
                }
            }
        }
        if ( value !== undefined ) {
            if ( value === null ) {
                jQuery.removeAttr( elem, name );
                return undefined;
            } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
                return ret;
            } else {
                elem.setAttribute( name, "" + value );
                return value;
            }
        } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
            return ret;
        } else {
            ret = elem.getAttribute( name );
            // Non-existent attributes return null, we normalize to undefined
            return ret === null ?
                undefined :
                ret;
        }
    },