2015-10-16 4 views
-1

Для назначения класса нам нужно создать забавный веб-сайт, который выделяет случайную функцию JavaScript. Мой сайт представляет собой генератор шутки moma joo, так что каждый раз, когда вы обновляете страницу, появляется новая шутка. Однако мой код не работает, и я не могу понять, почему это не так. Я новичок, поэтому любая помощь будет очень признательна! :)Генерировать произвольные предложения из массива Javascript

Вот мой код:

function setup() { 
    createCanvas(windowWidth, windowHeight, WEBGL); 

    smooth(); 
} 


function draw() { 
    background (255, 255, 255); 
} 

function getRandomSentence() { 
    var index= Math.floor(Math.random() * (maxSentences - 1)); 
    return sentences[index]; 
} 

var sentences= [ 
    'so fat not even Dora can explore her', 
    'so fat I swerved to miss her and ran out of gas', 
    'so smelly she put on Right Guard and it went left', 
    'so fat she hasn’t got cellulite, she’s got celluheavy', 
    'so fat she don’t need no internet – she’s already world wide', 
    'so hair her armpits look like Don King in a headlock', 
    'so classless she could be a Marxist utopia', 
    'so fat she can hear bacon cooking in Canada', 
    'so fat she won “The Bachelor” because she all those other bitches', 
    'so stupid she believes everything that Brian Williams says', 
    'so ugly she scared off Flavor Flav', 
    'is like Domino’s Pizza, one call does it all', 
    'is twice the man you are', 
    'is like Bazooka Joe, 5 cents a blow', 
    'is like an ATM, open 24/7', 
    'is like a championship ring, everybody puts a finger in her' 
], 

maxSentences = sentences.length; 

и вот мой HTML:

<html> 
    <head> 
     <title>new tab</title> 

     <meta charset="utf-8"> 

     <script src='./js/jquery-2.1.1.min.js' type='text/javascript'></script> 
     <script src='./js/p5.min.js' type='text/javascript'></script> 
     <script src='./js/sketch.js' type='text/javascript'></script> 
     <script src='./js/main.js' type='text/javascript'></script> 

     <link href='./css/reset.css' media='all' rel='stylesheet' type='text/css' /> 
     <link href='./css/main.css' media='all' rel='stylesheet' type='text/css' /> 
    </head> 
    <body> 

    </body> 
</html> 
+0

Вы вернули случайное предложение, и что тогда? Как текст будет нарисован на странице? – Nayuki

+1

Что значит «не работает»? Отправьте свой HTML здесь. – CurseStacker

+0

@CurseStacker здесь мой html – musst248

ответ

0

Я не знаю, почему я это делаю; я слишком мягкий для этого мира?

Вот примерный шаблон вы можете начать играть с

<!DOCTYPE html> 
<html> 
<head> 
<!-- You need UTF-8 here because you use some characters not in ASCII --> 
<meta http-equiv="content-type" content="text/html; charset=UTF8"> 
<script> 
/* 
    Math.random() returns a number between 0 and 1 excluding 1 itself. 
    That together with floor function returns a number between 0 and 
    max-1 (here max = sentence.length) and fits the zero-based numbering 
    of the elements in the array 
*/ 
function getRandomSentence() { 
    var index= Math.floor(Math.random() * (sentences.length)); 
    return sentences[index]; 
} 

var sentences= [ 
    'so fat not even Dora can explore her', 
    'so fat I swerved to miss her and ran out of gas', 
    'so smelly she put on Right Guard and it went left', 
    'so fat she hasn’t got cellulite, she’s got celluheavy', 
    'so fat she don’t need no internet – she’s already world wide', 
    'so hair her armpits look like Don King in a headlock', 
    'so classless she could be a Marxist utopia', 
    'so fat she can hear bacon cooking in Canada', 
    'so fat she won “The Bachelor” because she all those other bitches', 
    'so stupid she believes everything that Brian Williams says', 
    'so ugly she scared off Flavor Flav', 
    'is like Domino’s Pizza, one call does it all', 
    'is twice the man you are', 
    'is like Bazooka Joe, 5 cents a blow', 
    'is like an ATM, open 24/7', 
    'is like a championship ring, everybody puts a finger in her' 
]; 

function scribble(){ 
    // get the canvas element you want to write to 
    var canvas = document.getElementById("woodcut"); 
    // get a handle for the above canvas (here 2d only for simple text) 
    var context = canvas.getContext("2d"); 
    // the canvas is blank the first time only, so erase the content 
    // even if it is already blank, checking for it would be more 
    // complicated and slower, too 
    context.clearRect(0, 0, canvas.width, canvas.height); 
    // choose a font (you can choose the size also as you can see) 
    context.font = "30px Arial"; 
    // the letters are filled and they are filled in red 
    context.fillStyle = "red"; 
    // center the text horizontally 
    context.textAlign = "center"; 
    // put a random line in the middle of the canvas 
    // the +10 account for the fonttype's height 
    context.fillText(getRandomSentence(),0, canvas.height/2 + 10); 
} 
</script> 
</head> 
<body> 
An indifferent opinion<br> 
<canvas id="woodcut" width="1000" height="100" 
style="border:10px solid #665599;"> 
This text shows up if the canvas element is not supported 
</canvas> 
<br> 
<button onclick="scribble()">scribble</button> 


</body> 
</html> 

Это не лучший стиль, мягко говоря, это просто для игры вокруг.

Ой, слишком поздно! Еще раз!

+0

спасибо, это сработало! В любом случае я могу сделать предложение, не нажимая кнопку. Мое намерение состояло в том, чтобы каждый новый текст появлялся каждый раз, когда страница обновлялась. – musst248

+0

Вы можете использовать '', но некоторые пользователи могут отключить 'onload' (например, я) – deamentiaemundi

0

В вашем HTML файле, между <body> ... </body>, добавьте следующую строку кода:

<p id="MyRandomSentence"></p> 

В конце вашего файла JavaScript добавьте эти строки кода:

var element = $("#MyRandomSentence"); 
var sentence = getRandomSentence(); 
element.text(sentence); 
+0

спасибо! Я попробовал это и по какой-то причине все еще не сделал предложение. Мне нужно было вызвать текст в моем коде? – musst248

+0

Возможно, у вас синтаксическая ошибка. Вы видите в конце «предложений», перед «maxSentences», код говорит '],'? Пожалуйста, измените это на '];' – Nayuki

+0

Я исправил ошибку, но все же не появляюсь. Есть ли что-то, что мне нужно добавить в мой html-файл? Я пробовал кучу разных вещей, но ничего не заставляю предложения загружать – musst248

Смежные вопросы