繁体   English   中英

更改<a>javascript数组</a>中<a>元素的</a>文本

[英]change text of <a> element in javascript array

我有一个包含一堆锚元素的javascript数组,如下所示:

["<a href="#" id="id1">First anchor<a>", "<a href="#" id="id2">Second anchor<a>", "<a href="#" id="id3">Third anchor<a>"]

我想改变最后一个锚元素(第三个锚)中的文本,同时保持锚元素本身的属性不变(这意味着我想保持我的id和href属性完整)。 我该怎么做并返回更改的数组?

你没有一个锚元素数组,你有一个字符串数组。 而且你有一个很大的语法错误,因为你试图在双引号字符串中包含双引号而不转义它们。 无论如何:

var array = ["<a href=\"#\" id=\"id1\">First anchor<a>", "<a href=\"#\" id=\"id2\">Second anchor<a>", "<a href=\"#\" id=\"id3\">Third anchor<a>"];

array[2] = array[2].replace(/^(<[^>]+>)([^<]*)(<)/,
                            "$1" + "yourreplacementtexthere" + "$3");

演示: http//jsfiddle.net/byQcW/

有与使用数组中的一些语法问题'"也为关闭标签a是错的

array = ['<a href="#" id="id1">First anchor</a>', '<a href="#" id="id2">Second anchor</a>', '<a href="#" id="id3">Third anchor</a>'];
array[2] = array[2].replace(/(<a[^>]*?>)(.*)(<\/a>)/, '$1' + 'replacerstring' + '$3');

尝试这个:

var arr = ['<a href="#" id="id1">First anchor<a>', '<a href="#" id="id2">Second anchor<a>', '<a href="#" id="id3">Third anchor<a>']  
arr[2] = $(arr[2]).text('Your text here').prop('outerHTML');

如果你想要一个锚标签数组,那么jQuery的map方法会使这个变得微不足道:

var strings = ["<a href='#' id='id1'>First anchor</a>", "<a href='#' id='id2'>Second anchor</a>", "<a href='#' id='id3'>Third anchor</a>"];

var anchor_elements = $.map(strings, function(el){
  return $(el).get();
});

您现在可以使用jQuery轻松更改任何元素的文本:

$(anchor_elements[2]).text('New text');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM