jQuery:为每个表单字段提供一个按时间顺序递增的数字

发布于 2024-11-15 03:16:22 字数 530 浏览 10 评论 0原文

有一个动态生成的表单。对于每个表单输入字段('.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半边脸i 2024-11-22 03:16:22

或者您可以使用

$('.questions').each(function(index) {
 var num = index + 1;  
 $('<p class="num">'+num+'</p>').insertBefore($(this));
});

问题是,当您使用 insertBefore 方法时,您再次使用“.questions”选择器选择所有元素。而您实际上想将其插入到当前元素之前,该元素由 $(this) jquery 对象表示。

Or you can use

$('.questions').each(function(index) {
 var num = index + 1;  
 $('<p class="num">'+num+'</p>').insertBefore($(this));
});

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.

合约呢 2024-11-22 03:16:22

问题在于在每个回调中声明 num 。
将 num 的声明移至回调之外。

试试这个:

var num = 0;
$('.questions').each(function(index) {      
    num = index + 1;        
    $('<p class="num">'+num+'</p>').insertBefore(this);  
}); 

The issue is with declaring the num inside the callback of each.
Move the declaration of num to outside the callback.

Try this:

var num = 0;
$('.questions').each(function(index) {      
    num = index + 1;        
    $('<p class="num">'+num+'</p>').insertBefore(this);  
}); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文