2014-10-04 20 views
0

我需要在對話中追加div和h4。 我想要div convo-list從數組中追加文本,而我想追加自定義文本。JQuery附加多個元素但不同值的文本

在我的代碼上,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

只是改變這一行:

$('<h4>Name:</h4><div class="convo-list">').text(word).appendTo('.conversation'); 

到:

$('.conversation').append($('<h4>').text("Name:"), $('<div>').addClass('convo-list').text(word)) 
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..see不正是你想要什麼我的更新JSFIDLLE!

+0

'words.length'不是數組中單詞的長度;這是數組本身的長度。問題中的大部分代碼實際上來自我在[上一個問題]上提供的答案(http://stackoverflow.com/questions/26188735/jquery-random-words-without-repeating/26188808#26188808)。 – jmar777 2014-10-05 05:04:35

+0

嗯你是對的。我想昨天早上我沒有正確地喝我的咖啡:)問這個問題的人怎麼不接受一個答案,並問幾次同一個問題? – rorofromfrance 2014-10-05 08:56:32