我相信你正在尋找的是jQuery的.data()
:http://api.jquery.com/jQuery.data/
這是一種可能的方式是可以做到的:
<div id="songs"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(function() {
// The following array can be trivially generated directly from your data,
// by PHP's json_encode(), or your language's equivalent:
var songs = [
{
file: '/path/to/song.mp3',
title: 'A Day in the Life',
artist: 'The Beatles',
album: 'Sgt. Pepper\'s Lonely Hearts Club Band',
}
// ...
];
var wrap = jQuery('#songs');
for (var i=0, ii=songs.length; i<ii; i++) {
jQuery('<a></a>')
.text(songs[i].title)
.attr('href', songs[i].file)
.data('song-data', songs[i])
.click(click_handler)
.appendTo(wrap);
}
// then, you can retrieve the data like this:
function click_handler() {
var data = jQuery(this).data('song-data');
alert('Album was: '+data.album);
return false;
}
});
</script>
「最優雅」和「最好」的方式?這是乞求被關閉的主觀。定義你的優雅和「最佳」的措施。 – 2011-02-26 14:11:19