При беглом взгляде на страницу, на которую вы ссылались в своем вопросе, кажется, что разметка вокруг имен пользователей выглядит следующим образом (предположительно, с использованием вашего имени пользователя в качестве примера):
<a href="http://www.reddit.com/user/DiscontentDisciple" class="author id-t2_4allq" >DiscontentDisciple</a>
Если это так, и библиотека jQuery доступна (опять же, из вашего вопроса), один из подходов состоит в том, чтобы просто использовать:
var authors = [];
$('a.author').html(
function(i, h) {
var authorName = $(this).text();
if ($.inArray(authorName, authors) == -1) {
authors.push(authorName); // an array of author-names
}
return '<img src="path/to/' + encodeURIComponent(authorName) + '-image.png" / >' + h;
});
console.log(authors);
Проверка концепции JS Fiddle.
Или, аналогичным образом, просто используйте тот факт, что имя пользователя предсказуемо является последней частью URL-адреса в атрибуте href
элемента a
:
var authors = [];
$('a.author').html(
function(i, h) {
var authorName = this.href.split('/').pop();
if ($.inArray(authorName, authors) == -1) {
authors.push(authorName);
}
return '<img src="http://www.example.com/path/to/' + authorName+ '-image.png" />' + h;
});
console.log(authors);
Проверка концепции JS Fiddle.
Оба этих подхода помещают img
внутри элемента a
. Если вы хотите, чтобы это было перед элементом a
, просто используйте:
// creates an 'authors' variable, and sets it to be an array.
var authors = [];
$('a.author').each( // iterates through each element returned by the selector
function() {
var that = this, // caches the this variable, rather than re-examining the DOM.
// takes the href of the current element, splits it on the '/' characters,
// and returns the *last* of the elements from the array formed by split()
authorName = that.href.split('/').pop();
// looks to see if the current authorName is in the authors array, if it *isn't*
// the $.inArray returns -1 (like indexOf())
if ($.inArray(authorName, authors) == -1) {
// if authorName not already in the array it's added to the array using
// push()
authors.push(authorName);
}
// creates an image element, concatenates the authorName variable into the
// src attribute-value
$('<img src="http://www.example.com/path/to/' + authorName+ '-image.png" />')
// inserts the image before the current (though converted to a jQuery
// object in order to use insertBefore()
.insertBefore($(that));
});
console.log(authors);
Проверка концепции JS Fiddle.
Использованная литература:
person
David says reinstate Monica
schedule
19.08.2012