admin管理员组文章数量:1310027
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.
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.
Share Improve this question asked Sep 11, 2011 at 23:40 user547794user547794 14.5k38 gold badges108 silver badges152 bronze badges 02 Answers
Reset to default 2<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
.
本文标签: Javascriptchange value of variable on button clickStack Overflow
版权声明:本文标题:Javascript - change value of variable on button click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741858391a2401479.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论