Javascript - 单击按钮时更改变量的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7382058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - change value of variable on button click
提问by user547794
I have an 10 HTML buttons that I need to change the value of a javascript variable when clicked.
我有 10 个 HTML 按钮,需要在单击时更改 javascript 变量的值。
song2 = "mp3Player/kingRight.mp3";
function returnVar2(song2) { return this[song2]; }
Song2 needs a new URL depending on which button is clicked.
Song2 需要一个新的 URL,具体取决于单击的按钮。
Having a hard time figuring this out.
很难弄清楚这一点。
回答by kzh
<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
演示
回答by ?ime Vidas
HTML:
HTML:
<div id="mp3buttons">
<div title="mp3Player/kingRight.mp3">King Right</div>
<div title="mp3Player/AnotherSong.mp3">Another Song</div>
etc.
</div>
JavaScript:
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).
所以,你把你的按钮放在一个包装里。对于每个按钮,您将 URL 放在title
属性(或其他一些适当的属性)中。
In JavaScript code, you bind a click handler to the wrapper. The clicked button is referenced with e.target
.
在 JavaScript 代码中,您将点击处理程序绑定到包装器。单击的按钮引用为e.target
。