Массив кнопок, узнать индекс нажатой кнопки
Имеется массив кнопок button[]. Как узнать индекс нажатой кнопки? Два часа рылся в интернете, а так же на этом форуме, ответ не нашел. Я решил задачу, но считаю, что должно быть решение проще:
<script>
function ins(e){
var o = document.getElementsByName('butt[]');
for (i=0;i<o.length;i++){
if (o(i) == e) alert ('Индекс ' + i);
}
}
</script>
<input type='button' name='butt[]' value='ok1' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok2' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok3' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok4' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok5' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok6' onclick='ins(this)'/>
|
function ins(t){
alert(t.value.substring(2,3));
}
|
на чистом js без цикла вроде никак, не прибегая к ручному заданию номеров и их извлечению (например, как показал vadim5june)
Цитата:
добавить return, o.length - в отдельную переменную (хотя и Фленаган и Илья Кантор почему-то этого не делают, хотя по идее это выражение вычисляется каждый раз http://es5.javascript.ru/x12.html#x12.6.3 Цитата:
видимо из-за того, что машины стали слишком производительными :) PS: атрибут onclick уже давно признак плохого стиля, не |
Цитата:
Цитата:
Спасибо за детальные замечания, поправил код:
function ins(e){
var o = document.getElementsByName('butt[]');
var l = o.length;
for (i=0; i<l; i++){
if (o[i] == e) {var ind = i; break;}
}
alert ('Индекс ' + ind);
}
|
Цитата:
|
что-нибудь типа такого
<form id="form">
<input type='button' name='butt[]' value='ok1'/>
<input type='button' name='butt[]' value='ok2'/>
<input type='button' name='butt[]' value='ok3'/>
<input type='button' name='butt[]' value='ok4'/>
<form>
<script>
window.onload = function () {
function index(element, collection) {
var len = collection.length;
for (var i = 0; i < len; i++) {
if (element == collection[i]) {
return i;
}
}
}
document.getElementById('form').onclick = function (e) {
var e = e || event;
var target = e.target || e.srcElement;
if (target.type == 'button') {
alert(index(target, document.getElementsByName('butt[]')));
}
}
}
</script>
Цитата:
см. ненавязчивый javascript |
Цитата:
|
Цитата:
<script>
function ins(e){
var o = document.getElementsByName('butt[]');
var l = o.length;
for (i=0; i<l; i++){
if (o[i] == e) {var ind = i; break;}
}
alert ('Индекс ' + ind);
}
</script>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
<input type='button' name='butt[]' value='ok' onclick='ins(this)'/>
|
Цитата:
|
Цитата:
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script type="text/javascript">
function key(self) {
var doc=document.getElementsByName(self.name);
for(var i in doc) {
if(doc[i]===self) {
alert(i);
}
}
}
</script>
<input type="button" name="butt[]" value="ok0" onclick="key(this)">
<input type="button" name="butt[]" value="ok1" onclick="key(this)">
<input type="button" name="butt[]" value="ok2" onclick="key(this)">
</body>
</html>
|
| Часовой пояс GMT +3, время: 04:44. |