Reputation: 1279
I want to manipulate the attributes of an object when it is created dynamically.
In the code given below, I would like to increase the like attribute by calling the corresponding functions of the object. However the elements are created dynamically and passing a this in the onclick function will only refer to the anchor tag.
The idea is similar to this forum wherein each question has various ideas that can be approved or disapproved. How can I manipulate each object's attribute independently?
function idea(idea) {
this.ideatext = idea;
this.like = 0;
this.str = "\
<div class = 'entered'> \
<div class = 'text'> " + this.ideatext + "</div> \
<div class = 'anchors'> \
<a href = '' onclick = 'increase()'> Approve </a> \
<a href = '' onclick = 'decrease()'> Disapprove </a> \
</div> \
</div>";
this.increase = function() {
this.like++;
}
this.decrease = function() {
this.like--;
}
}
var ideaobj1 = new idea(someidea1);
var ideaobj2 = new idea(someidea2);
Upvotes: 0
Views: 137
Reputation: 269
If you dynamically create javascript code and you want it to refer to other javascript code, you have to know the variable names. No way around that.
<script type="text/javascript">
function idea(varName, text)
{
this.varName = varName;
this.ideatext = text;
this.like = 0;
this.str = "\
<div class = 'entered'> \
<div class = 'text'> " + this.ideatext + "</div> \
<div class = 'anchors'> \
<a href = '' onclick = '" + this.varName + ".increase()'> Approve </a> \
<a href = '' onclick = '" + this.varName + ".decrease()'> Disapprove </a> \
</div> \
</div>";
this.increase = function ()
{
this.like++;
return false;
}
this.decrease = function ()
{
this.like--;
return false;
}
}
var wing = new idea("wing", "a wing is ...");
var wheel = new idea("wheel", "a wheel is ...");
</script>
And use some sort of centralized storage for the created objects. Maybe like this:
var brain = new Object();
brain["wing"] = new idea("brain.wing", "a wing is ...");
brain["wheel"] = new idea("brain.wheel", "a wheel is ...");
Upvotes: 1
Reputation: 11873
You can create elements with the document.createElement
method:
var newDiv = document.createElement("div");
And then modify newDiv
before adding the element to the document.
More info about document.createElement
here: https://developer.mozilla.org/es/docs/DOM/document.createElement
Upvotes: 0
Reputation: 7819
Instead of adding an onclick attribute, give the tags a class (I used classes increase and decrease in this example). Then add the following jquery code
$(document)
.on('click', '.increase', function() {
alert('increase function');
});
.on('click', '.decrease', function() {
alert('decrease function');
});
Upvotes: 0