[英]How do I add dynamic text to a HTML tag?
I am new to JS. 我是JS新手。 I want to add (elements) words from an array on mouse click into HTML.
我想从鼠标单击数组中的数组中添加(元素)单词。
var pos = document.querySelector('span'); for (let i = 0; i < array length; i++) { button.addEventListener('click', function() { pos.innerHTML = array[i]; }); }
<p> the word generated is <span></span></p> <button>go</button>
let array1 = ['1', '2', '3']; var pos = document.getElementById('output'); var button = document.getElementById('btn'); button.addEventListener('click', function() { for (var i = 0; i < array1.length; i++) { pos.innerHTML = pos.innerHTML + array1[i]; } });
<p>the word generated is <span id="output"></span></p> <button id="btn">go</button>
This will display all element of array on button click. 单击按钮将显示数组的所有元素。
Try this, it randomly displays a word in span
element. 尝试此操作,它将在
span
元素中随机显示一个单词。
var words = ['rest', 'fever', 'ball', 'sky', 'earth', 'moon', 'sun', 'temper']; var button = document.querySelectorAll('button').item(0); button.addEventListener('click', function(event){ let span = document.querySelectorAll('p span').item(0); let randomWord = words[Math.round(Math.random() * (words.length - 1))]; span.textContent = randomWord; });
p span { font-weight: bold; color: red; }
<p> the word generated is <span></span></p> <button>go</button>
Or with Jquery: 或使用Jquery:
<p> the word generated is <span></span></p>
<button id="btn">go</button>
Code: 码:
var array = ['test','test2'];
$('#btn).on('click', function () {
array.forEach(function(entry) {
$('p span).append(entry+' ');
})
})
If you are looking for random text generations, you can use random function to generate random array indexes. 如果要查找随机文本,可以使用random函数生成随机数组索引。
button.addEventListener('click', function() {
pos.innerHTML = arr[Math.floor(Math.random() * Math.floor(arr.length))]
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.