更改<a> element in javascript array</a>的文字

时间:2013-04-21 07:14:41

标签: javascript jquery

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

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

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

4 个答案:

答案 0 :(得分:4)

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

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/

答案 1 :(得分:3)

数组中与使用'"相关的语法问题很少,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');

答案 2 :(得分:1)

试试这个:

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');

答案 3 :(得分:0)

如果你想要一个锚标签数组,那么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');