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

时间:2013-04-22 01:11:35

标签: javascript jquery

这就是我从html usng Jquery中取出文本的方法:

$(".text").each(function(){

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

我的问题是,如果我希望文本是一个网址,那么它不会显示为链接,而是一个字符串添加到文本变量。如何显示链接?如何将其添加为文本的href?

输出应该是这样的:

文字+网址

而不是将文字链接为网址:"<a href=\""+link+"\">"+texts+"</a>"

3 个答案:

答案 0 :(得分:1)

使用.attr()这样的功能。

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

但是这只会有效,如果你有锚标签,你可以动态创建一个锚标签。

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

答案 1 :(得分:1)

你可以使用class = text这样的每个元素作为这样的链接,假设你有一些你要用超链接包装的元素。我不是百分百肯定这就是你要找的东西。

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

答案 2 :(得分:1)

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

this.href="yoururl"

您不必遍历在attr期间调用的followng jquery代码,只需设置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;
        }
    },
相关问题