Javascript - change value of variable on button click
I have an 10 HTML buttons that I need to change the value of a javascript variable when clicked.
song2 = "mp3Player/kingRight.mp3";
func开发者_StackOverflow社区tion returnVar2(song2) { return this[song2]; }
Song2 needs a new URL depending on which button is clicked.
Having a hard time figuring this out.
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<script>
var b1 = document.getElementById('b1'), b2 = document.getElementById('b2');
var x = "Hello!";
function showX() {
alert(x);
}
b1.onclick = function() {
x = "button one";
showX();
};
b2.onclick = function() {
x = "button two";
showX();
};
</script>
Demo
HTML:
<div id="mp3buttons">
<div title="mp3Player/kingRight.mp3">King Right</div>
<div title="mp3Player/AnotherSong.mp3">Another Song</div>
etc.
</div>
JavaScript:
var mp3buttons = document.getElementById( 'mp3buttons' );
mp3buttons.onclick = function ( e ) {
var url = e.target.title;
// do stuff with this URL
};
So, you put your buttons inside a wrapper. For each button, you place the URL inside the title
attribute (or some other appropriate attribute).
In JavaScript code, you bind a click handler to the wrapper. The clicked button is referenced with e.target
.
精彩评论