使用jQuery将元素名称分配给多个元素名称作为前缀 [英] Assign Element Name to multiple element's names as a Prefix using jQuery

查看:99
本文介绍了使用jQuery将元素名称分配给多个元素名称作为前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,允许动态生成内容,我想在所有动态内容名称创建时/在发布之前/在接受之前,都给它们加上隐藏元素的名称.

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.

在执行该脚本之前,<input>元素必须具有名称.必须将<script>标记放置在结束body标记之前,或者使用window.onload来确认DOM已加载.

The <input> elements must have a name before this script gets executed. The <script> tag must be placed just before the closing body tag or use window.onload instead, to confirm that the DOM has loaded.

这篇关于使用jQuery将元素名称分配给多个元素名称作为前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆