Как добавить рандомайзер на основе js в html
Знатоки js подскажите как оформить. Есть html:
<h5><a href="tel:+12345678900" id="chat"> +12-34-567-89-00 </a></h5>
<a href="whatsapp://send?phone=12345678900" id="chat"></a>
<a href="viber://chat?number=12345678900" id="chat"></a>
Нужно номер телефона во все три тега подставлять рандомно, т.е одну из этих переменных a=12345678900, b=00123456789, c=98765432100. В Python это делается с помощью модуля random:
a=['12345678900', '00123456789', '98765432100']
tel=a[random.randint(0,2)]
Как это сделать с помощью js и как переменную tel вставить в вышеуказанный html?
Ответы (1 шт):
Автор решения: WalkMess
→ Ссылка
ваш html сюда
const nodeL = document.querySelectorAll('a');
const getRandom = (min, max) => Math.floor(Math.random() * (max - min)) + min;
for (let node of nodeL) {
const href = node.href;
node.href = href + getRandom(0000, 99999);
}
Однако на практике будет приблизительно такое.
const nodeL = document.querySelectorAll("a");
const getRandom = (min, max) => Math.floor(Math.random() * (max - min)) + min;
const hrefs = [
{
path: {
text: "tel:",
href: '+'
}
},
{
path: {
text: 'whatsapp',
href: '://send?phone'
},
},
{
path: {
text: 'viber',
href: '://chat?number'
}
}
]
hrefs.forEach(({path}, index) => {
nodeL[index].href = `${path.text}${path.href}${getRandom(1e9, 1e9)}`;
});