Reputation: 11
I am populating a list from php, and using the onClick event to run a javascript function once the link has been clicked, I need to associate the value for the engine to the link that has been clicked..and at the moment it is by having the value assigned to the TITLE tag as shown in the code below, I know this is not the proper way of doing this, so instead how could I store the values on the page and be able to access them in the javascript function, so depending on the link that is clicked it retrieves the corresponding value, I was thinking of a storing them as a javascript array or object? or something associative so I could access them from the id of the link so if the link is clicked with the id of e213, once it is clicked then inside the javascript function I could use, 'objectname'.value + 'idvariable', and the property names would be "value" + the id's of the links.
Any help would be great thanks!
<?php
connect();
$sql = "SELECT engine_id, engine, image, value FROM engines";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result) ) {
echo "<li><a style=\"color:#FF6600;\" id='e".$row['engine_id']."' title = '".$row['value']."' onclick='return enginepic(this)' onfocus='this.hideFocus=true;' href='".$row['image']."'>".$row['engine']."</a></li>";
}
?>
Upvotes: 0
Views: 95
Reputation: 1959
You could just pass in the data you want to the enginepic
function as a parameter.
Your onclick
would look something like this
onclick='return enginepic(this, \''" . $row['value'] . "\')
And your function declarations would look something like
function enginepic(oLink, data){
.
.
.
}
Upvotes: 0
Reputation: 14917
HTML5 allows attributes that start data- for this case. Eg...
<div data-whatever-property="some value" id="some-id"></div>
You can then fetch this data using:
document.getElementById('some-id').getAttribute('data-whatever-property')
Or with jquery...
$('#some-id').attr('data-whatever-property')
Or even easier...
$('#some-id').data('whateverProperty')
Notice that the data method on jQuery turns one-two-three
to oneTwoThree
. This is conforming to the dataset part of the html5 spec.
Also, consider adding your events via JavaScript rather than using onclick/onfocus/etc attributes. For a list of links, you'll get better performance out of delegated events, jquery makes these easy.
Upvotes: 2