[英]How to replace text with links using javascript?
這是我從html usng Jquery中提取文本的操作:
$(".text").each(function(){
var texts = items[textCount]['data']['title'];
$(this).text(texts);
textCount = textCount + 1;
});
我的問題是,如果我希望文本是url,那么它不會顯示為鏈接,而且還會顯示一個添加到texts變量中的字符串。 如何顯示鏈接? 如何將其作為href添加到文本中?
輸出應該是這樣的:
文字+網址
而不是將文本鏈接為url: "<a href=\\""+link+"\\">"+texts+"</a>"
像這樣使用.attr()
函數。
$(this).attr("href", "your link");
但這只有在您有錨標簽的情況下才有效,如果沒有錨標簽,則可以即時創建錨標簽。
$(this).html("<a href=\""+link+"\">"+texts+"</a>");
您可以使每個帶有class = text的元素成為這樣的鏈接,它假定您具有某種要用超鏈接包裝的元素。 我不是100%肯定這是您要尋找的。
$('.text').wrap('<a href="http://yourlinkhere.com"></a>');
你可以做。 注意:-這比attr()更有效,因為您直接處理object屬性。
this.href="yoururl"
您不必遍歷在attr期間調用的以下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;
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.