简体   繁体   中英

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";
 function 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM