由于我的问题标题可能有点不清楚(我尝试过最好),以下是我正在尝试做的事情。
我有一个表单元素(比如user_info表单),其中这些表单元素将由java脚本为不同的用户生成,并显示在不同的js标签中(例如:dojo标签)。
生成表单元素后,我需要对在 user_info表单中定义的中定义的不同html元素执行的用户操作做出反应。在这种情况下,我需要确定用户正在处理的上下文(user_info表单元素)。最简单的示例是如何检索正在执行用户操作的表单的表单ID。
根据我的理解,我不能简单地从表单id中检索,因为现在DOM树包含来自元素的相同表单实例。所以,无论如何,我可以根据用户对其输入元素的操作来识别表单上下文。
谢谢。
答案 0 :(得分:1)
从任何表单元素中,只需检查元素的“form”属性,即可找到包含元素的表单。如果您正在处理事件,那么事件对象将为您提供目标。如果您的表单中包含“提交”元素,那么本机浏览器行为将仅提交一个受影响的表单。
编辑因此,例如,如果你有一个“click”事件的处理程序以某种方式绑定:
function clickHandler(ev) {
ev = ev || window.event;
var theForm = ev.target.form; // find the form from the target element
if (form) {
// do whatever you need to do to here
}
}
答案 1 :(得分:0)
如果你有多个<form></form>
标签的表单结构和用户一样多,并且每个表单实例中都有操作按钮
方法1
- 您可以使用此答案中给出的代码Finding the form Id in javascript获取您单击的操作按钮的父表单元素。它包含javascript和jquery代码。如果您有相应的表单ID,则可以操作其数据。
方法2
- 假设您使用javascript生成表单元素,您可能会将一些数字指定为表单名称的一部分。说form_22
(对于ID为22的用户),form_24
等,您可以将相同的数字作为ID的一部分分配给这些表单中的操作按钮,因此在生成和分配后,您的表单看起来像此: -
<form name="user_22">
following are input fields
<input "data1_22">
<input "data2_22">
following are action inputs
<input name="edit_22" id="edit_22" onclick="editForm();" />
<input name="some_other_action_24" id="some_other_action_24" onclick="otherActionForm();" />
</form>
<form name="user_24">
following are input fields
<input "data1_24">
<input "data2_24">
following are action inputs
<input name="edit_24" id="edit_24" onclick="editForm(this);" />
<input name="some_other_action_24" id="some_other_action_24" onclick="otherActionForm();" />
</form>
因此,您可以在js函数中准备表单ID并对表单数据进行操作
function editForm(object)
{
var formNumber = str_replace("edit_","",object.name);
//Get javascript str_replace from https://github.com/kvz/phpjs/raw/master/functions/strings/str_replace.js
var formName = "user_"+formNumber;
//Get form params and do what you want
document.formName.data1_+formNumber;
document.formName.data2_+formNumber;
}