问题描述
我有一个网页,允许动态生成内容,我想在所有动态内容名称创建时/在发布之前/在接受之前,都给它们加上隐藏元素的名称.
I have a webpage that allows for dynamically generated content, I want to prefix all the dynamic content names with the name of the hidden element when they're created/before post would be acceptable.
这些动态添加的文本框所在的类在页面上共享,因此不能轻松地用于标识.
The classes that these dynamically added textboxes are in, are shared across the page so can't easily be used to identify.
我无法使它正常工作,我需要检查它们是否具有前缀,如果没有,请添加前缀
I cannot get this to work, I would need to check whether they have the prefix, if they don't, add the prefix
小提琴:
https://jsfiddle.net/ycjrunja/2/
jQuery
$(// can't use class).attr(); // do I need to use this method for each <td> ?
当前生成的标记:
<input type=hidden name="main[xyz]" />
<input type=button name="addRow" />
<table>
<tr>
<td><input type=text name="tb1r1" /></td>
<td><input type=text name="tb2r1" /></td>
</tr>
<tr>
<td><input type=text name="tb1r2" /></td>
<td><input type=text name="tb2r2" /></td>
</tr>
</table>
理想的标记
<input type=hidden name="main[xyz]" />
<input type=button name="addRow" />
<table>
<tr>
<td><input type=text name="main[xyz]tb1r1" /></td>
<td><input type=text name="main[xyz]tb2r1" /></td>
</tr>
<tr>
<td><input type=text name="main[xyz]tb1r2" /></td>
<td><input type=text name="main[xyz]tb2r2" /></td>
</tr>
</table>
推荐答案
使用此方法:
$("td input").each(function(){
$(this).attr("name",$("input:hidden").attr("name")+$(this).attr("name" ));
});
说明:
第一行遍历<td>
元素内的所有<input>
元素.
The first line iteratres through all the <input>
elements inside <td>
elements.
第二行将<input type = "hidden>"
的name
赋予正在迭代的<input>
元素的name
,并将其分配给当前迭代的元素name
.
The second line concantates the name
of the <input type = "hidden>"
with the <input>
element's name
which is being iterated and assigns it to the name
of currently iterated element.
最后一行结束函数和each()
方法.
The last line ends the function and each()
method.
这篇关于使用jQuery将元素名称分配给多个元素名称作为前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!