2016-05-27 4 views
0

Я пытаюсь добавить функцию GetQuotes() к кнопке. Каждый раз, когда вы нажимаете кнопку, он отображает новый текст или в этом случае новые кавычки. В настоящее время на кнопке отображается только ответ undefined.Моя функция возвращает только неопределенные значения

Моей логикой было создание массива со строками кавычек. Сначала я попытался использовать цикл for для генерации случайных кавычек. Однако это явно не имело никакого смысла. Затем я использовал Math.random() для генерации случайных котировок. Затем я попробовал добавить свой класс h2 под названием stuff. Кнопка называется quotes. Когда вы нажимаете кнопку, она меняет текст в h2.

Вот Javascript:

function getQuotes(){ 
    var quotes = [ 
    "Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.Buddha", 
    "Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.Unknown", 
    "To be happy, we must not be too concerned with others.Albert Camus", 
    "If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else." 
    ] 

    var result = quotes[Math.floor(Math.random() * quotes.length)]; 

    document.getElementById("stuff").innerHTML = result; 
} 

Вот JQuery:

$(document).on('click', '#quotes', function() { 
    document.getElementById("stuff").innerHTML = getQuotes(); 
}); 

И HTML:

<div class="row"> 
    <div class="col-12-xs"> 
    <h2 id="stuff" class="text-center"><em> Here is some Text </em> </h2> 
    </div> 
</div> 
+0

$ ('# вещи').HTML (getQuotes()); – circusdei

+3

Внутри вашей функции удалите 'document.getElementById (" stuff "). InnerHTML = result;' и замените его на 'return result;' –

+0

Можете ли вы объяснить, почему это сработало? – Codes316

ответ

3

Ваша функция ничего не возвращает, поэтому JS будет вместо этого дайте вам undefined. Поскольку последняя строка вашей функции напрямую устанавливает элемент, тогда обработчик jQuery снова устанавливает его (до неопределенного значения), вы потеряете значение и увидите только неопределенное.

То, что вы сейчас делаете, по существу:

// as part of getQuotes: 
    document.getElementById("stuff").innerHTML = result; 
    // return undefined; 

// in the handler 
document.getElementById("stuff").innerHTML = undefined; // the output from getQuotes 

Вы можете либо изменить свою функцию:

function getQuotes(){ 
    var quotes = [ "Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.Buddha", 
"Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.Unknown", 
"To be happy, we must not be too concerned with others.Albert Camus", 
"If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else."] 

return quotes[Math.floor(Math.random() * quotes.length)]; 
} 

или вы можете оставить innerHTML = foo в функции и изменить Обработчик jQuery до:

$(document).on('click', '#quotes', function() { 
    getQuotes(); 
}); 
+0

О, я вижу, это имеет гораздо больший смысл. Спасибо за совет! – Codes316

0

getQuotes должен return result в конце вместо того, чтобы устанавливать внутреннийHTML stuff div.

В добавлении, getQuotes - это настройки innerHTML в div stuff и возвращении undefined (так как он не имеет явного оператора возврата). После того, как это произойдет, ваш обработчик OnClick является перезапись innerHTML с undefined

В качестве альтернативы, вы можете просто установить innerHTML от getQuotes, а не в обработчике щелчка, но я не думаю, что это хорошая идея, так как это делает ваш getQuotes функция сложнее протестировать.

0

Ваша функция ничего не возвращает, поэтому, когда вы устанавливаете значение innerhtml на значение требуемой кавычки, оно делает это в первый раз, но затем, поскольку функция ничего не возвращает, undefined возвращается из функции, которая установлена в innerhtml в коде jquery. Вы можете сделать следующие изменения в коде: -

function getQuotes(){ 
 
    var quotes = [ 
 
    "Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.Buddha", 
 
    "Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.Unknown", 
 
    "To be happy, we must not be too concerned with others.Albert Camus", 
 
    "If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else." 
 
    ] 
 

 
    var result = quotes[Math.floor(Math.random() * quotes.length)]; 
 

 
    return result; 
 
}