我正在尝试获取单击按钮的值,或者确定单击了哪个按钮。
从下面的代码中,我得到了所有值,但我只想要点击的按钮。
<script type="text/javascript">
function GetCheckedFruits () {
var elements = document.getElementsByName ("fruit");
for (var i=0; i < elements.length; i++) {
if (elements[i].click) {
alert ("The " + (i+1) + ". button is click");
}
}
}
</script>
HTML:
<input id="Text1" name="fruit" type="button" value="apple" onclick="GetCheckedFruits ()" /><br />
<input id="Text1" name="fruit" type="button" value="banana" onclick="GetCheckedFruits ()" /><br />
<input id="Text1" name="fruit" type="button" value="blackberry" onclick="GetCheckedFruits ()" /><br />
我哪里错了?
答案 0 :(得分:1)
变化
if (elements[i].click) {
alert ("The " + (i+1) + ". button is click");
}
到
if (elements[i].type == 'button') {
alert ("The " + elements[i].value + " button is click");
}
就是这样。
修改强>
试试这个
function GetCheckedFruits(clickedButton){ 警告(&#34;&#34; + clickedButton.value +&#34;。按钮点击&#34;); } }并添加如下按钮
<input type="button" value="Button1" onclick="{GetCheckedFruits(this);}" />
<input type="button" value="Button2" onclick="{GetCheckedFruits(this);}" />
<input type="button" value="Button3" onclick="{GetCheckedFruits(this);}" />
答案 1 :(得分:0)
如果要在单击按钮时提醒消息,则必须使用如下事件:
<script type="text/javascript">
function GetCheckedFruits () {
var elements = document.getElementsByName ("fruit");
for (var i=0; i < elements.length; i++) {
elements[i].onclick = function() {
// You can put anything you want here
// the variable `this` is the clicked button
alert ("The " + this.value + " button is click");
}
}
}
</script>
编辑:
如果您正在使用复选框并且正在尝试获取所选的水果,这将有效:
<script type="text/javascript">
function GetCheckedFruits () {
var elements = document.getElementsByName ("fruit");
for (var i=0; i < elements.length; i++) {
if (elements[i].checked == 1) {
alert ("The " + elements[i].value + " button is click");
}
}
}
</script>