jQuery:为每个表单字段提供一个按时间顺序递增的数字
有一个动态生成的表单。对于每个表单输入字段('.questions')。我想显示字段的编号(按时间顺序)。所以第一个字段显示 1,第二个字段显示 2 结束,依此类推。
我想我几乎已经在这段代码中得到了它,但现在它为每个元素提供了每个数字,因此输入字段一= 1234和二= 1234,其中应该是一= 1二= 2。
$('.questions').each(function(index) {
var num = index + 1;
('<p class="num">'+num+'</p>').insertBefore('.questions');
});
现在它可以正常工作了:
$('.questions').each(function(index) {
var num = index + 1;
('<p class="num">'+num+'</p>').insertBefore(this);
});
There is a dynamically generated form. For each form input field ('.questions'). I would like to show the number of the field(chronological). So the first field shows 1 the second 2 end so on.
I think I've almost got it in this code, but now it give for each element every number so input field one =1234 and two=1234 where it should be one=1 two=2.
$('.questions').each(function(index) {
var num = index + 1;
('<p class="num">'+num+'</p>').insertBefore('.questions');
});
now it works right:
$('.questions').each(function(index) {
var num = index + 1;
('<p class="num">'+num+'</p>').insertBefore(this);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者您可以使用
问题是,当您使用 insertBefore 方法时,您再次使用“.questions”选择器选择所有元素。而您实际上想将其插入到当前元素之前,该元素由 $(this) jquery 对象表示。
Or you can use
The issue is that when you are using the insertBefore method, you are again selecting all the elements by using the '.questions' selector. Whereas you actually want to insert it just before the current element, which is represented by the $(this) jquery object.
问题在于在每个回调中声明 num 。
将 num 的声明移至回调之外。
试试这个:
The issue is with declaring the num inside the callback of each.
Move the declaration of num to outside the callback.
Try this: