如何使用jquery给输入的ID名称添加数字
How to use jquery to add numbers to input ID name
我正在使用生成具有给定 ID 名称的输入字段的 wordpress 插件 - fieldname15_6
虽然我在循环中使用代码,但对于每个 post 它正在创建具有相同 ID 名称的输入字段。当然这是个问题。我有大约 10 个具有相同 ID 名称的输入,我相信它会导致显示问题。不管我的 CSS 规则如何,字体大小和间距似乎有点随机。
无论如何,我需要一种方法来自动将数字 1+ 添加到具有该 ID 名称的任何已创建输入。我尝试使用以下代码,但它什么也没做 --
$("input[id^='fieldname15_6']").attr('id', function (i) {
return "fieldname15_6" + ++i;
});
我做错了什么?
谢谢
试试这个:
var $files = $('body').find("input").attr("id","fieldname15_6");
$files.each(function(index)
{
newIndex = $(this).attr("id") + index;
$(this).attr("class", newIndex );
});
var i = 1;
$("input#fieldname15_6").each(function(){
$(this).attr('id', function(i) {
return "fieldname15_6" + ++i;
});
});
这对你有帮助......
$("input[id^='fieldname15_6']").each(function(i){
$(this).attr('id', $(this).attr('id') + i);
});
简单的答案是不要。对于这种类型的东西,您应该使用 类,这就是它们的用途。然后您可以使用各种方法来定位和处理单个元素,例如 .eq()
$('#result').html($('.fieldname15_6').eq(2).val()); // eq is 0 based array syntax so 2 will be the 3rd element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="fieldname15_6" value="first value">
<input type="text" class="fieldname15_6" value="second value">
<input type="text" class="fieldname15_6" value="third value">
<br>
<br>
<br>
<br>
<div id="result"></div>
我正在使用生成具有给定 ID 名称的输入字段的 wordpress 插件 - fieldname15_6
虽然我在循环中使用代码,但对于每个 post 它正在创建具有相同 ID 名称的输入字段。当然这是个问题。我有大约 10 个具有相同 ID 名称的输入,我相信它会导致显示问题。不管我的 CSS 规则如何,字体大小和间距似乎有点随机。
无论如何,我需要一种方法来自动将数字 1+ 添加到具有该 ID 名称的任何已创建输入。我尝试使用以下代码,但它什么也没做 --
$("input[id^='fieldname15_6']").attr('id', function (i) {
return "fieldname15_6" + ++i;
});
我做错了什么? 谢谢
试试这个:
var $files = $('body').find("input").attr("id","fieldname15_6");
$files.each(function(index)
{
newIndex = $(this).attr("id") + index;
$(this).attr("class", newIndex );
});
var i = 1;
$("input#fieldname15_6").each(function(){
$(this).attr('id', function(i) {
return "fieldname15_6" + ++i;
});
});
这对你有帮助......
$("input[id^='fieldname15_6']").each(function(i){
$(this).attr('id', $(this).attr('id') + i);
});
简单的答案是不要。对于这种类型的东西,您应该使用 类,这就是它们的用途。然后您可以使用各种方法来定位和处理单个元素,例如 .eq()
$('#result').html($('.fieldname15_6').eq(2).val()); // eq is 0 based array syntax so 2 will be the 3rd element
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="fieldname15_6" value="first value">
<input type="text" class="fieldname15_6" value="second value">
<input type="text" class="fieldname15_6" value="third value">
<br>
<br>
<br>
<br>
<div id="result"></div>