通过<td>单击控制台返回随机值.log



我一直在搜索如何从控制台.log中的表中返回值。 例如:

如果我有一个数组,我可以像这样从数组中生成一个随机值:

var questionsarray = ["index 0, how to use javascript console to update variable?"];
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
function quizloops() {
return(questionsarray[getRandomInt(0,2)]) }

当我在Javascript控制台中时,我使用quizloops(),并从数组中获取一个随机索引。

如何从表中生成相同的内容? 如果有一个按钮可以使用它来生成带有 console.log 的值,那就太好了。

<table id="tbl1">
<tr>
<td id="1>Henk</td>
<td class="day">tuesday</td>
<td>sample1</td>
<td>sample2</td>
<td>sample3</td>
<td>sample4</td>
<td></td>
<td id="number_2">667</td>
</tr>
</table>

谢谢!

从表中获取所有td。由于您使用的是jquery$("#tbl1").children('tbody').children('tr').children('td')因此它将是一个jquery对象。

tds.length将给出td总数。将此值传递给getRandomInt。假设您的表可以有 0td因此最小值为 0。

生成随机数后,使用相同的 jquery 对象使用text()方法检索文本。

希望这个片段会有用

function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
$('#gen').on('click', function() {
var tds = $("#tbl1").children('tbody').children('tr').children('td')
var randomValue = getRandomInt(0, tds.length)
console.log($(tds[randomValue]).text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl1">
<tr>
<td id="1">Henk</td>
<td class="day">tuesday</td>
<td>sample1</td>
<td>sample2</td>
<td>sample3</td>
<td>sample4</td>
<td></td>
<td id="number_2">667</td>
</tr>
</table>
<button type="button" id='gen'>Generate</button>

最新更新