问题
I have a basic unordered list with an input field/form below it. I would like the user to be able to type in the total number of list items they would like to see and on click, the results would show. Here is my HTML:
<div id="boxes">
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
<div class="box1"></div>
</div>
<form id="four" action="#">
<input type="text" placeholder="Type items per page"></input>
<button>Submit</button>
</form>
And my JQuery:
$("#four button").on('click', function(){
var buttonValsss = $("#four input").val();
var boxes = $("#boxes");
var generate = "<div class='box1'></div>";
boxes.html('');
boxes.append(generate);
boxes.children().html("<p>" + text + "</p>");
});
I am storing the variable from the user input (number of items), clearing out all of the list items in #boxes, and then appending one list item on click, setting the text from a global variable from a previous function. On click, I want the variable generate to be appended x number of times, as defined by the variable buttonValsss
What is the best way to go about this?
回答1:
try using for loop:
$("#4 button").on('click', function(){
var buttonValsss = $("#4 input").val();
var boxes = $("#boxes");
boxes.empty(); // you can use empty() method
for (i = 0; i < buttonValsss; i++ ) {
boxes.append('<div class="box1"></div>');
}
});
http://jsfiddle.net/z2Wc3/
来源:https://stackoverflow.com/questions/11286407/generating-list-item-x-number-of-times-based-on-user-input