我有一大块用PHP生成的HTML代码。
HTML如下所示:
<input type="text" id="10"><button onclick="process()">send</button>
<input type="text" id="11"><button onclick="process()">send</button> <!-- and so on until id=N -->
PHP代码类似于:
<?php while ($row = $result->fetch_assoc()) { ?>
<input type="text" id="<?=$row['id']?>">
<button onclick="process()">send</button>
<br>
<?php } ?>
假设如果用户单击SEND按钮,input标记的值将传递给process()函数。
这就是我陷入困境的地方:我不知道我应该在process()函数中的getElementById中指定输入的确切ID,因为我不知道按下了哪个按钮。
如果有任何帮助,我将不胜感激。
虽然这不是首选方式,但如果您想坚持使用内联事件处理程序,您可以执行以下操作:
function process(elem){
alert(elem.previousSibling.value);
}
<input type="text" id="10"><button onclick="process(this)">send</button>
<input type="text" id="11"><button onclick="process(this)">send</button>
请注意
基于Gecko的浏览器在文档中插入文本节点以表示源标记中的空白。因此,获得了一个节点例如,使用Node.firstChild或Node.previousSibling可以指代空白文本节点,而不是作者的实际元素想要得到。
以前的同级
与前面的答案一样,理想情况下应该远离内联绑定事件。但是,如果必须这样做,解决方案是两个。默认情况下,如果事件对象没有被任何一个重写,则会将其传递给事件处理程序方法。
这样的方法将为您提供足够的关于事件的目标元素的信息。(行为可能因浏览器而异,因此可能需要对其进行彻底测试。)
function EventHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
现在,只需执行target.id就可以调用gettheid,或者基本上可以获取任何属性值。