+ 2
How to insert data into an element without changing it using JavaScript
I want output like this: "L2 U B' R2 D2 U' R D U2 F'" https://code.sololearn.com/W4uEea72A3DW/?ref=app
4 ответов
+ 3
Change
$("#res").html("R");
to
$("#res").append("R ");
+ 3
Thx)
+ 1
You can simplify your code, so your JS section could look like this:
array = ["R ", "R' ", "R2 ", "L ", "L' ", "L2 ", "U ", "U' ", "U2 ", "F ", "F' ", "F2 ", "D ", "D' ", "D2 " ]; // array with elements
$(function(){
$("#gen").click(function rand(){
arr_random=Math.floor(Math.random()*15); // generates random index of array
$("#res").append(array[arr_random]); // appends element of array with random index
});
});
It does the same thing.
+ 1
Moreover, you can do this without jQuery, so you don't need to include jQuery file in head section, and you will need to apply onclick event to your button like this:
<button id="gen" onclick="rand()">
And your JS section will look like this:
array = ["R ", "R' ", "R2 ", "L ", "L' ", "L2 ", "U ", "U' ", "U2 ", "F ", "F' ", "F2 ", "D ", "D' ", "D2 "]; // array with elements
function rand(){
arr_random=Math.floor(Math.random()*15); // generates random index of array
res=document.getElementById("res");
res.innerHTML+=array[arr_random]; // a+=x means a=a+x
}