gpt4 book ai didi

javascript - 如何将字符串数组相应地分配给子元素?

转载 作者:行者123 更新时间:2023-11-29 21:15:11 25 4
gpt4 key购买 nike

如果我有字符串 var mydata="a1,a2,a3, ,a5,b1,b2,b3,b4,b5" 并且我需要分配给下面的这个元素怎么办?:-

Parent Index: 0 (div classname="parts")
.serialno="a1"
.modelno="a2"
.section="a3"
.subsection=" " -empty value
.incharge="a5"

Parent Index: 1 (div classname="parts")
.serialno="b1"
.modelno="b2"
.section="b3"
.subsection="b4 "
.incharge="b5"

我已经知道的是如何将字符串数组直接分配给元素,如下所示:-

    var mydata = $("#txtproduction").val();
var gdata = mydata.split(',').length / 5; //get how many group



if (gdata = 1) {
$.each(mydata.split(','), function (index, value) {
if (index == 0) { $('.serialno').val(value); }
if (index == 1) { $('.modelno').val(value); }
if (index == 2) { $('.section').val(value); }
if (index == 3) { $('.subsection').val(value); }
if (index == 4) { $('.incharge').val(value); }
});
}

但是当元素在父元素中有子元素时,我不知道如何处理它......

       if (gdata >1){
//if more than 1 group data - how to handle loop assign value to element accondingly??

}

请帮帮我,我已经想了很多天了,但还是想不出如何解决这个问题。提前感谢您阅读和回答我的问题。

最佳答案

元素结构如下:

<div class="parts">
<input type="text" class="serialno">
<input type="text" class="modelno">
<input type="text" class="section">
<input type="text" class="subsection">
<input type="text" class="incharge">
</div>
<div class="parts">
<input type="text" class="serialno">
<input type="text" class="modelno">
<input type="text" class="section">
<input type="text" class="subsection">
<input type="text" class="incharge">
</div>

下面的代码应该可以工作:

var mydata = $("#txtproduction").val();            
var arr = mydata.split(',');
$('.serialno').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5]);});
$('.modelno').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+1]);});
$('.section').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+2]);});
$('.subsection').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+3]);});
$('.incharge').each(function(i, o) {$(this).val(arr[$(this).parent().index(".parts")*5+4]);});

如果结构不同,请纠正我的理解。检查here.

关于javascript - 如何将字符串数组相应地分配给子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39694461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com