[英]Add random class to an Appended div ? (jquery)
這是我正在使用的對象的所有代碼,但我認為這只是您真正需要幫助的“屏幕上創建建築物”部分。
我的目標是在不說class =“ House houseRed”的地方,而是說class =“ House +'randomClass'”等,該變量保存我的其他類名(我總共有5個)。 這是我正在開發的迷你游戲,我需要根據它們的類名生成的建築物具有不同的外觀。
//CREATE BUILDING IN MEMOMORY
function CreateHouseInMemory() {
//GET VALUES
var sAddress = $("#HouseAddress").val();
var sUniqueId = getUniqueId();
var iMaxResidents = $('input[name=housemaxresidents]').val();
var oHouse = {
sType: "House",
sAddress: sAddress,
sId: sUniqueId,
iMaxResidents: iMaxResidents,
Residents: aResidents = [],
babyInHouse: false
};
oCity.aBuildings.push(oHouse);
console.dir(oCity.aBuildings);
return oHouse;
}
//CREATE BUILDING IN SCREEN
function CreateHouseInScreen(oHouse)
{
$("#City").append('<div id="' + oHouse.sId + '" class="House houseRed" title="' + oHouse.sAddress + '"></div>');
$(".House").draggable();
$(".House").droppable();
}
;
//SPAWN BUILDING
$("#BtnCreateHouse").click(function() {
var oHouse = CreateHouseInMemory();
CreateHouseInScreen(oHouse);
});
創建目標類名稱的數組
var array = ['one', 'two','three','four', 'five'];
//then
var random = array[Math.floor(Math.random() * array.length)]
您可以按以下方式隨機添加類:
function CreateHouseInScreen(oHouse)
{
var classes = ['houseRed', 'houseBlue', 'houseGreen'];
var randomIndex = Math.floor(Math.random() * classes.length);
var div = $('<div id="' + oHouse.sId + '" class="House" title="' + oHouse.sAddress + '"></div>');
div.addClass(classes[randomIndex]);
$("#City").append(div);
$(".House").draggable();
$(".House").droppable();
}
像這樣
var classesnames = ['toto', 'titi', 'tata', 'tutu'],
classrandom = classesnames[Math.floor(Math.random() * classesnames.length)];
$("#City").append('<div id="' + oHouse.sId + '" class="House '+ classrandom +'" title="' + oHouse.sAddress + '"></div>');
您可以使用類似
i = parseInt(Math.random() * 4)
為類數組生成數組索引,例如
classArray = ['class1', 'class2', 'class3', 'class4', 'class5']
obj.className = classArray[i]
或將整數轉換為字符串並將其附加到常量字符串,例如
obj.className = "myClass" + i.toString().
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.