2013-04-22 83 views
0

這是我做的從HTML USNG取出文本的Jquery:如何用JavaScript代替鏈接文本?

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

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

我的問題,如果我想的文本是一個鏈接,那麼它不顯示爲鏈接,但還增加了一個字符串到文本變量。我如何顯示鏈接?如何將它作爲href添加到文本中?

輸出應該是這樣的:

文字+網址

,而不是文字被鏈接的網址:"<a href=\""+link+"\">"+texts+"</a>"

回答

1

使用.attr()功能是這樣的。

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

但是,這隻會工作,如果你有一個錨標記,如果不是你可以動態創建一個錨標記。

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

這將創建一個文本鏈接。我想要這樣的東西:文本+鏈接,而不是文本的鏈接。 – Hick 2013-04-22 01:59:05

+0

用所需的HTML輸出更新您的問題。 – Starx 2013-04-22 02:01:00

+0

已經更新了一下。不知道這是否正是你想要的。 – Hick 2013-04-22 02:05:35

1

你可以用類=文本的每個元素像這樣的鏈接,假設你有某種元素,你會用一個超鏈接來包裝。我不是100%確定這是你正在尋找的。

$('.text').wrap('<a href="http://yourlinkhere.com"></a>'); 
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; 
     } 
    }, 
+0

但你假設attr存在。 – Hick 2013-04-22 01:50:16

+0

@Hick它只是作爲一個JavaScript對象處理。如果href不存在,則會添加href屬性。這是你的問題嗎?而且對於href屬性,即使你沒有在html標籤中提及它,對象也會始終具有href屬性。你可以自己檢查一下,如果我錯了,請糾正我的錯誤... – PSL 2013-04-22 01:53:51

+0

感謝您的幫助。我會看看。 – Hick 2013-04-22 02:03:35