Reputation: 126
I'm trying to figure out how to make the following code work:
<ul>
<li id='anvil1' class='locked' onclick='anvil1.countCheck("anvil1", "defense", 10, event.button);'>+10 Defensive Ability</li>
<li id='anvil4' class='locked' onclick='anvil4.countCheck("anvil4", "[\"defense\", \"constitution\"]", [10, 20], event.button);'>+15 Defensive Ability <br />+20 Constitution</li>
</ul>
These links are accessing methods from the the star object. I need the 2nd and 3rd parameters to be arrays, because they have a variable number of values. For instance, the first star, anvil1, has one stat (defense) and one value (10). The fourth star has two stats (defense, constitution) and two values (10, 20). I believe the number of stats/values can go up to 3.
So far, if I try to call stats[0]
the value that's returned is simply the first letter?
alert('Stats: ' + stats[0]);
results in an alert box with Stats: d
or Stats: [
I'm not sure how to fix this, and any advice would be greatly appreciated!
Upvotes: 0
Views: 1803
Reputation: 8980
I wouldn't pass the parameters like that. You could add one eventlistener for anvil elements and pass the parameters with data attributes.
Please have a look at the following snippet or in this jsfiddle.
var anvil = {
countCheck: function(e) {
var props = this.dataset.props.split(','),
points = this.dataset.points.split(',');
console.log(this.id, props, points);
}
}
// add eventlisteners
var anvils = document.getElementsByClassName('anvil');
for (var i=0; i< anvils.length; i++) {
anvils[i].addEventListener('click', anvil.countCheck);
}
<ul>
<li id='anvil1' class='anvil locked' data-props="defense" data-points="10">+10 Defensive Ability</li>
<li id='anvil4' class='anvil locked' data-props="defense,constitution" data-points="10,20">+15 Defensive Ability <br />+20 Constitution</li>
</ul>
Upvotes: 0
Reputation: 7041
Can you spot the difference ?
"[\"defense\", \"constitution\"]"
is a string and
[10, 20]
is an array. Obviously you want your 2nd parameter as an array too so you need to change your call to
anvil4.countCheck("anvil4", ["defense", "constitution"], [10, 20], event.button);
Upvotes: 1
Reputation: 161
you have your array in quotes. when you use [n] on a string it returns the n'th character. you can also get rid of the string escapes (like elclanrs said)
Upvotes: 0