在jQuery中循环和设置名称和ID [英] Looping and setting name and id in jquery

查看:155
本文介绍了在jQuery中循环和设置名称和ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一种向表中动态添加行的方法.每个表拖包含两个文本字段(collectionText和Link)

I have created a method to dynamically add rows to a table . each table tow contains two text fields(collectionText and Link)

<tr>
<td>
  <input type="text" size="30" id="txtCollectionText" name="txtCollectionText" />
</td>
 <td>
 <input type="text" size="30" id="txtLink" name="txtLink" />
 </td>
</tr> 

下面是我的剧本

   function addRow() {
            var row = $('#table tbody>tr:last').clone(true).insertAfter('#table tbody>tr:last');
            var index = $("#table tbody>tr").length;
            $("td:eq(0)", row).text(index);
            $("td:eq(1) input", row).attr("name", "txtCollectionText" + index).attr("id", "txtCollectionText" + index)
            $("td:eq(2) input", row).attr("name", "txtLink" + index).attr("id", "txtLink" + index)
        }

这会将索引添加到新添加的输入中,但不添加到现有输入中.我的要求是索引应从零开始. 例如,如果我默认情况下有2行,则添加第三行将给我collectiontext4和link4,但是我想为所有行从0 -4开始编号...任何想法??

This will add the index to newly added inputs.but not to the existing ones . my requirement the indexes should start form zero . for example if i have 2 rows by default ,adding third row will give me collectiontext4 and link4 , but i want numbering for all my rows starting from 0 -4 ...any ideas ??

推荐答案

要将代码绑定到document.ready事件:

To bind the code to your document.ready event:

$(function() {
    $('#table tr').each(function(index, element)
    {
       var e = $(element);
       e.find('td:eq(0)').text(index);
       var first = 'txtCollectionText' + index.toString();
       var second = 'txtLink' + index.toString();
       e.find('td:eq(1) input').attr({name: first, id: first});
       e.find('td:eq(2) input').attr({name: second, id: second});
    });
}

如果放置在脚本标签中,则此代码将在浏览器完成文档构建后立即自动执行.这就是$(function() {})表示法的作用-它是$(document).bind('ready', function() {})的简写.

If placed inside a script tag, this code will automatically execute as soon as the document is finished being constructed by the browser. That's what the $(function() {}) notation does -- it's shorthand for $(document).bind('ready', function() {}).

这篇关于在jQuery中循环和设置名称和ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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