Javascript: Finding and replacing dynamically generated text
I know this is something that is fairly well documented, but I'm having some serious trouble applying any of it to this situation.
I need to come up with a way of essentially saying: If 'phone number' appears on page -> randomly replace it w开发者_JS百科ith either image1, image2 or image3. And I need it to happen five times with one of three possible images to be displayed in place of each of the 5 different 'phone number'.
Originally I considered starting by creating 2 separate arrays. One array for the phone numbers and one array for the images to replace it, but I was completely stumped as to how I could randomly apply one of three images to a single array element.
Any ideas or inspiration is very much appreciated.
The main bind I should think will be locating the phone numbers, unless you convert the whole page in to HTML code, and place it all back in, that would not be ideal.
You can keep a list of phone-number/image pairings together by making either two arrays that share the same indexing, or an array of tuples (just an object with two entries).
var phoneReplacements = [
{ 'phone': '01234 567890', 'image': 'phone-support.jpg' },
{ 'phone': '01234 000000', 'image': 'phone-customer.jpg' },
{ 'phone': '01234 999999', 'image': 'phone-technical.jpg' }
];
Then you can loop through them finding and replacing.
for (replacementIndex in phoneReplacements) {
var cPhoneNumber = phoneReplacements[replacementIndex]['phone'];
var cImageSrc = phoneReplacements[replacementIndex]['image'];
/* find all elements containing phone number text and loop */
/* get content as HTML */
var cContent = cElement.innerHTML;
/* replace text with image */
var cNewContent = cContent.replace("/" + cPhoneNumber + "/g", '<img src="' + cImageSrc + '" alt="' + cPhoneNumber + '" />');
/* set new content */
cElement.innerHTML = cNewContent;
/* repeat for all matching elements */
}
Using jQuery would make things a bit easier, the trick is finding the phone numbers, which basically means searching all text nodes on the page.
精彩评论