2017-06-22 9 views
0

console.logのテーブルから値を返す方法を探しています。​​の値をconsole.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> 

ありがとうございます!

答えて

0

tdをテーブルから取得します。 jqueryを使用しているので$("#tbl1").children('tbody').children('tr').children('td')はjqueryオブジェクトになります。

tds.lengthは、合計でtdとなります。この値をgetRandomIntに渡します。あなたのテーブルは0 tdなので、最小値は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>

関連する問題