[英]how to get index of array in javascript whihout knowing its value
i am creating an array of textboxes.我正在创建一个文本框数组。 and each box has a corresponding del and edit option.并且每个框都有对应的删除和编辑选项。
for(i=0;i<5;i++)
{
<input type='text' id='pp_insti' name='pp_insti[]' value='"+institute+"' style='display:none;'>
<input type='button' class='edit-button' id='pp_edit name='pp_edit[]' onclick='pp_edit();'/>
<input type='button' class='del-button' id='pp_del name='pp_del[]' onclick='pp_del();'/>
}
what value of index should i pass for pp_edit so i know which pp_inst[] to edit.我应该为 pp_edit 传递什么索引值,所以我知道要编辑哪个 pp_inst[]。
can anyone help.. thanks谁能帮忙..谢谢
You're trying to create several textboxes with the same ID
( pp_insti
).您正在尝试创建多个具有相同ID
( pp_insti
) 的文本框。 This is not allowed.这是不允许的。
Instead, you could give them IDs such as pp_insti_1
, pp_insti_2
etc, based on the value of i
.相反,您可以根据i
的值为它们提供 ID,例如pp_insti_1
、 pp_insti_2
等。 You could then pass the value of i
to the edit and delete functions as well, to be able to find the text box of interest.然后,您也可以将i
的值传递给编辑和删除函数,以便能够找到感兴趣的文本框。
You don't need to pass a value, because the onclick handler is run with an event variable automatically passed to it.您不需要传递值,因为 onclick 处理程序在运行时会自动传递一个事件变量。 Therefore change your function definition of pp_edit()
to pp_edit(ev)
, and then inside the function use elem=ev.target
, where elem will be the DOM element that was clicked on.因此,将pp_edit()
的 function 定义更改为pp_edit(ev)
,然后在 function 中使用elem=ev.target
,其中 elem 将是被点击的 DOM 元素。
Alternatively, you could pass the this
keyword to each call of pp_edit: onclick='pp_edit(this);
或者,您可以将this
关键字传递给 pp_edit 的每个调用: onclick='pp_edit(this);
, then define pp_edit: pp_edit(obj)
. ,然后定义 pp_edit: pp_edit(obj)
。 Now in pp_edit, obj
refers to the clicked element.现在在 pp_edit 中, obj
指的是被点击的元素。
The third alternative is to set the onclick handlers programatically, instead of in-line:第三种选择是以编程方式设置 onclick 处理程序,而不是内联:
for(....){
elem=document.createElement('...');
elem.onclick=pp_edit;
}
Now, when pp_edit is called, it will be within the context of the clicked element, and inside pp_edit, the this
keyword will refer to the clicked element.现在,当调用 pp_edit 时,它将在被点击元素的上下文中,而在 pp_edit 中, this
关键字将引用被点击元素。
NOTE: as another user pointed out, your code is invalid, but I am assuming you posted it that way to get your point across.注意:正如另一位用户指出的那样,您的代码无效,但我假设您以这种方式发布它以表达您的观点。 If not, you definitely need to lookup functions like document.createElement()
.如果没有,您肯定需要查找诸如document.createElement()
之类的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.