2013-07-26 4 views
0

Permettez-moi de commencer par vous dire que je suis nouveau à travailler avec jQuery et que je n'ai pas beaucoup d'expérience en programmation en général. C'est la première fois que j'essaie d'apprendre cela, et j'apprécierais donc de garder des explications et des solutions assez simples si possible.Insérez une valeur aléatoire dans une autre valeur aléatoire, jQuery

Je travaille sur la génération d'un bloc complet de texte à partir de phrases aléatoires. Cela fonctionne bien. Cependant, j'aimerais pouvoir insérer une valeur aléatoire dans un autre pour plus de "caractère dynamique". Par exemple, je voudrais utiliser des noms aléatoires dans d'autres variables aléatoires.

Par exemple, je voudrais créer à partir du tableau var Malsattning une sortie qui a lu: « La vision est de [insérer le nom de Var Foretagsnamn] pour créer une attitude positive envers la marque » Je veux aussi garder la capacité de générer un nom de Var Foretagsnamn par lui-même (comme avec tous les mots/phrases générés en cours).

C'est un peu difficile à expliquer, alors j'ai créé un jsFiddle pour que vous puissiez vérifier si le code ci-dessous ne suffira pas; http://jsfiddle.net/lennyekberg/gFUxG/

///////////////////////////// 
// Foretagsnamn (Name) // 
///////////////////////////// 
    var Foretagsnamn = [ 
    'Lisa', 
    'Ann', 
    'Matt', 
    'Carl', 
    'Sara', 
    'Ron' 
    ], 
    //the current sentences length 
    maxForetagsnamn = Foretagsnamn.length; 

// get and return a random sentences from array 
function getRandomForetagsnamn() { 
    //calculate a random index 
    var rndIdxForetagsnamn = Math.floor(Math.random()*(maxForetagsnamn)); 
    //return the random sentence 
    return Foretagsnamn[rndIdxForetagsnamn];       
} 

//show a random sentences in a DOM selector 
function showRandomForetagsnamn(selector){ 
    var randomForetagsnamn = getRandomForetagsnamn(); 
    $(selector).html(randomForetagsnamn); 
} 


/////////////////////////////////////////////////// 
// Foretagsbeskrivning (Workdescription) // 
/////////////////////////////////////////////////// 


var Foretagsbeskrivning = [ 
    'is an icecream vendor', 
    'is a plumber', 
    'organizes charity events', 
    'build hybrid cars' 
    ], 
    //the current sentences length 
    maxForetagsbeskrivning = Foretagsbeskrivning.length; 

//get and return a random sentences from array 
function getRandomForetagsbeskrivning() { 
    //calculate a random index 
    var rndIdxForetagsbeskrivning = Math.floor(Math.random()*(maxForetagsbeskrivning)); 
    //return the random sentence 
    return Foretagsbeskrivning[rndIdxForetagsbeskrivning];       
} 


//show a random sentences in a DOM selector 
    //vad är en DOM selector, för alla taggar i html eller? 
function showRandomForetagsbeskrivning(selector){ 
    var randomForetagsbeskrivning = getRandomForetagsbeskrivning(); 
    $(selector).html(randomForetagsbeskrivning); 
} 


//////////////////////////// 
// Målsättning (Goal) // 
//////////////////////////// 


var Malsattning = [ 
    'The vision is to dominate the market in three years', 
    'The vision is to create a positive attitude towards the brand', 
    'The goal is to create a huge profit in the next two years', 
    'Ett mål för det fortsatta arbetet är att kunna hävda sig mot konkurrenter och skeptiker' 
    ], 
    //the current sentences length 
    maxMalsattning = Malsattning.length; 

//get and return a random sentences from array 
function getRandomMalsattning() { 
    //calculate a random index 
    var rndIdxMalsattning = Math.floor(Math.random()*(maxMalsattning)); 
    //return the random sentence 
    return Malsattning[rndIdxMalsattning];       
} 


//show a random sentences in a DOM selector 
    //vad är en DOM selector, för alla taggar i html eller? 
function showRandomMalsattning(selector){ 
    var randomMalsattning = getRandomMalsattning(); 
    $(selector).html(randomMalsattning); 

} 


//////////////////////////////////////////////////// 
// Målsättning, genomförande (Goal, execution) // 
//////////////////////////////////////////////////// 


var Malsattninggenomforande = [ 
    'with the implementation of sustainable solutions', 
    'by using viral marketing', 
    'by creating new demands on the market', 
    'with a nation wide marketing campaign' 
    ], 
    //the current sentences length 
    maxMalsattninggenomforande = Malsattninggenomforande.length; 

//get and return a random sentences from array 
function getRandomMalsattninggenomforande() { 
    //calculate a random index 
    var rndIdxMalsattninggenomforande = Math.floor(Math.random()*(maxMalsattninggenomforande)); 
    //return the random sentence 
    return Malsattninggenomforande[rndIdxMalsattninggenomforande];       
} 


//show a random sentences in a DOM selector 
    //vad är en DOM selector, för alla taggar i html eller? 
function showRandomMalsattninggenomforande(selector){ 
    var randomMalsattninggenomforande = getRandomMalsattninggenomforande(); 
    $(selector).html(randomMalsattninggenomforande); 

} 



///////////////////////////////////////////// 
// Målsättning, resultat (Goal, result) // 
///////////////////////////////////////////// 


var MalsattningResultat = [ 
    'which will result in new buisness opportunities', 
    'and in time reach a wider audience', 
    'that will create a positive attitude to the business' 
    ], 
    //the current sentences length 
    maxMalsattningResultat = MalsattningResultat.length; 

//get and return a random sentences from array 
function getRandomMalsattningResultat() { 
    //calculate a random index 
    var rndIdxMalsattningResultat = Math.floor(Math.random()*(maxMalsattningResultat)); 
    //return the random sentence 
    return MalsattningResultat[rndIdxMalsattningResultat];       
} 


//show a random sentences in a DOM selector 
    //vad är en DOM selector, för alla taggar i html eller? 
function showRandomMalsattningResultat(selector){ 
    var randomMalsattningResultat = getRandomMalsattningResultat(); 
    $(selector).html(randomMalsattningResultat); 

} 



////////////////// 
// Output // 
////////////////// 


//used to output the different sentences 
//used by .click & .ready beneath 
var outputLista = function() { 
    showRandomForetagsnamn(".foretagsnamn"); 
    showRandomForetagsbeskrivning(".foretagsbeskrivning"); 
    showRandomMalsattning(".malsattning"); 
    showRandomMalsattninggenomforande(".malsattninggenomforande");     
    showRandomMalsattningResultat(".malsattningresultat"); 
    } 


$('.rndButton').click(function(e){ 
    outputLista(); 
    console.log('get random sentences at click...'); 
}); 

//generates random sentences when the page loads 
$('.rndButton').ready(function(e){ 
    console.log('get random sentences at page load...'); 
    outputLista(); 
}); 

Répondre

0

Je pense que votre meilleur b et serait l'utilisation d'espaces réservés. Si vous modifiez par ex.

'The vision is to dominate the market in three years' 

à

'The vision is for @@[email protected]@ to dominate the market in three years' 

vous pourriez faire quelque chose comme

var randomName = getRandomForetagsnamn(); 
var randomMalsattning = getRandomMalsattning(); 
var result = randomMalsattning.replace('@@[email protected]@', randomName); 
alert(result); 

Vous avez juste besoin de faire en sorte que l'espace réservé est quelque chose qui se produit nulle part ailleurs dans le texte - facilement réalisable si vous utilisez des caractères spéciaux pour remplir l'espace réservé.

EDIT: J'ai créé un jsFiddle très basique à des fins de démonstration: http://jsfiddle.net/8YjVc/1/

+0

Merci, cela fonctionne bien. [Fait un jsFiddle rapide] (http://jsfiddle.net/lennyekberg/nLq6n/) si quelqu'un d'autre veut jeter un coup d'oeil. Une pensée pour une utilisation future; est-il possible de remplacer plus d'un mot, comme 'var result = randomMalsattning.replace ('@@ personne @@', randomName, @@ car @@, randomCar);'? – Lenny

+0

Vous pouvez faire 'randomMalsattning.replace ('@@ personne @@', randomName) .replace ('@@ car @@', randomCar); ' Fondamentalement, la fonction' replace' accepte deux paramètres, le premier étant une expression régulière qui peut être une chaîne simple, la seconde étant la valeur avec laquelle vous voulez remplacer l'espace réservé. La valeur de retour est également une chaîne, vous pouvez donc simplement chaîner plusieurs appels à la fonction de remplacement si vous souhaitez effectuer plusieurs remplacements. – UweB

+0

Super, c'est exactement ce que je voulais dire. Infiniment reconnaissant! – Lenny

0

Vous pouvez utiliser une fonction split pour mettre le nom dans le résultat. Here est le violon.

Pour utiliser facilement la scission, créez un var pour le nom en dehors des fonctions:

var name; 

Ensuite, modifiez vos résultats en ajoutant des caractères que vous diviser (ici les personnages sont « [] »):

var Malsattning = [ 
    'The vision is for [] to dominate the market in three years', 
    'The vision is for [] to create a positive attitude towards the brand', 
    'The goal is for [] to create a huge profit in the next two years', 
    'Ett mål för det fortsatta arbetet är att kunna hävda sig mot konkurrenter och skeptiker' 
], 

Enfin, divisé et montrer le résultat:

function showRandomMalsattning(selector){ 
    var randomMalsattning = getRandomMalsattning(); 
    var split = randomMalsattning.split('[]'); 
    $(selector).html(split[0] + name + split[1]); 
} 
+0

Cette solution fonctionne, pour autant que je peux voir, bien - Sauf « [] » est pas présent dans une phrase dans le tableau. Par exemple, la quatrième phrase de votre exemple écrit "Carlundefined" ou "Saraundefined" etc. à la fin, car il n'a pas été scindé dans le tableau. Existe-t-il un moyen d'utiliser des phrases avec et sans '[]' avec cette solution? – Lenny

Questions connexes