如何在生成块后在块内添加数字?像第一个块说1,第2个,依此类推。这是我目前的全部代码。只需输入您希望在输入中生成的块数。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Traversering og elementskapelse</title>
</head>
<body>
<h1>Traversering og elemenskapelse</h1> <!--Titles/text -->
<p>Antall div'er å generere:
<input id="numberInput" type="text" name="inputField" style=width:200px;>
<input id="numberButton" type="button" onclick="BLOCKGENERATOR_APP.init();" value="Generer">
</p>
<section id="blockSection"></section>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// App-module pattern of main function
var BLOCKGENERATOR_APP = {
$blockSection: null, //Divs
blocks: null, //Array
init: function(){ //init
var BG = BLOCKGENERATOR_APP; //Shortens the code further
var setSection = function(){ //Sets functions to html-section with id "blockSection"
BG.$blockSection = $("#blockSection");
}();
var spawnInput = function(){ //Initialize function for spawning the divs
var input = document.getElementById("numberInput").value;
BG.blocks = generator.fetchBlocks("div", input);
BG.$blockSection.append(BG.blocks);
}();
var setEvents = function(){ // Functions for div-interaction
$("div", BG.$blockSection).on("mouseenter", function() { // When mouse touch div, the opacity renders to 1
$(this).animate({
opacity: 1.0
}, 2000, function() {}); // Set 2 sec transition time
});
$("div", BG.$blockSection).on("click", function() { // On click, color of targetet div will be changed to MediumOrchid
$(this).css("background-color", "MediumOrchid");
});
$("div", BG.$blockSection).on("dblclick", function() { // On double-click, color of targetet div will be changed to yellow
$(this).css("background-color", "yellow");
});
}();
}//--end init
};//--end BLOCKGENERATIR_APP
// Function for generating divs \\
var generator = (function(){
var fetchBlocks = function(tag, input){
var blocks = []; // Array of generated divs
for(var i = 0; i < input; i++){ // Generates until input value is met
var $newBlock = $("<" + tag + ">") //
.css( // Alters css properities of divs
{
"width": "80px",
"height": "80px",
"margin": "10px",
"background-color": "Red",
"float": "left",
"opacity": "0.5" // Initial amount that's altered during event
}
);
blocks.push($newBlock); // Adds instance of block to array
}
return blocks; // Returns array
}//--end fetchBlocks
return {fetchBlocks: fetchBlocks} // Returns the blocks
}());//--end generator
</script>
</body>
</html>
&#13;
答案 0 :(得分:2)
.text(i);
只需在将css应用于generator
函数中生成的代码后添加此内容..
var $newBlock = $("<" + tag + ">").css({
"width": "80px",
"height": "80px",
"margin": "10px",
"background-color": "Red",
"float": "left",
"opacity": "0.5"
}).text(i);