我需要在对话中追加div和h4。 我希望div convo-list能够附加数组中的文本,而我想在其中添加自定义文本。
在我的代码中,div convo-list和h4上的文本是相同的。帮助我。
$(document).ready(function() {
var words = ['a', 'b', 'c'];
var getRandom = function() {
var idx = Math.floor(Math.random() * words.length);
return words.splice(idx, 1)[0];
};
var appendIfMore = function() {
var word = getRandom();
if (!word) alert('a');
$('<h4>Name:</h4><div class="convo-list">').text(word).appendTo('.conversation');
var delay = Math.round(Math.random() * (5000 - 500)) + 100;
setTimeout(appendIfMore, delay);
};
appendIfMore();
});
答案 0 :(得分:0)
只需更改此行:
$('<h4>Name:</h4><div class="convo-list">').text(word).appendTo('.conversation');
为:
$('.conversation').append($('<h4>').text("Name:"), $('<div>').addClass('convo-list').text(word))
答案 1 :(得分:0)
您可以通过这种方式更好地选择数组中的随机项:
var getRandom = function() {
return words[Math.floor(Math.random()*words.length)]
};
你必须获取两个不同的word
,所以你不能只将它保存到一个变量中!:
var appendIfMore = function() {
var wordConvo = getRandom(),
wordName = getRandom();
$("<h4/>", { html: "Name: " + wordName }).appendTo(".conversation");
$("<div/>", { class: "convo-list", html: wordConvo }).appendTo(".conversation");
var delay = Math.round(Math.random() * (5000 - 500)) + 100;
setTimeout(appendIfMore, delay);
};
希望它有所帮助!
我为你创建了一个JSFIDDLE:http://jsfiddle.net/5o2uoqbL/1/
编辑:我刚看到你想要两个不同的名字和convo的单词。请看我更新的JSFIDLLE,它完全符合你的要求!