Reputation: 4232
I have an 'a' list like this:
<div id="page">
<a href="#">2</a>
<a href="#">3</a>
<a href="#">4</a>
</div>
For now I have to set the list as HTML, but since I'm going to use ~500 times 'a' I need it be generated as result of some jquery event.
The total amount of 'a' tags is given by SomeFunction();
How can I generate (for instance on .click) the exact amount of 'a' tags given by SomeFunction();
?
ps The html numbers should also be generated.
Upvotes: 0
Views: 119
Reputation: 30002
Why do you need to wrap all this in jQuery, as it can all be created with ease and more efficiently by accessing the DOM yourself?
function SomeFunction( len ) {
var i,
a,
coll = document.createDocumentFragment();
for (i = 1; i <= len; i+=1) {
a = document.createElement("a");
a.href = "#";
a.appendChild(document.createTextNode( i ));
coll.appendChild( a );
}
document.getElementById("page").appendChild( coll );
}
SomeFunction(5);
A few things that you do not want to be doing:
example: http://jsfiddle.net/ShvUc/
Upvotes: 2
Reputation: 39261
// Returns an array with num links
function createLinks(num) {
var links = [];
for(var i = 0; i < num; i++) {
links.push($("<a>").attr("href", "#").text(i));
}
return links;
}
// When someButton is clicked
$(someButton).on("click", function() {
// Create as many links as specified by SomeFunction and append them to #page
$("#page").append(createLinks(SomeFunction()));
});
Upvotes: 0
Reputation: 15579
function getATagCount()
{
return 100;
}
$("<click on what>").click(function()
{
var aArray=[];
for(var i=0;i<getATagCount();i++)
{
aArray.push('<a href="#">'+i+'</a>');
}
$("#page").append(aArray.join(" "));
});
is this what you want?
Upvotes: 0
Reputation: 4696
function generateAnchors(count){
var target = $('#page'), str='';
for(var i = 0; i < count; i+=1){
str += "<a href='#'>" + i + "</a>";
}
target.empty().append(str);
}
Upvotes: 0
Reputation: 337637
Assuming SomeFunction()
simply returns an integer:
$("#myButton").click(function() {
var count = SomeFunction();
var aElements = "";
for (var i = 0; i < count; i++) {
aElements += "<a href=\"#\">" + i + "</a>";
}
$("#page").append(aElements);
});
DO NOT call append()
500 times as others have suggested - it will be incredibly slow.
Upvotes: 4
Reputation: 29935
$('#myButton').click(function(){
var number = SomeFunction();
for(var i=0; i<number; i++){
$('#page').append('<a href="whatever.com">Text here</a>');
}
});
Upvotes: 0