如何使用文档优化此 java 脚本代码。?

How do I optimise this java script code with document.?

我是 JS 的新手,不明白 do..while 等在这里是如何工作的。我该如何优化这段代码?我正在做的事情是否正确(在每个具有 id a1-7 的元素中设置变量 a[...]b[...]?我有一个 list grouplist items 里面有#a1-7#b1-7。我正在做的是用值设置数据值,以用数据值替换数据目标(其他文本元素)。

document.getElementById('a1').setAttribute('data-value', a[0])
document.getElementById('a2').setAttribute('data-value', a[1])
document.getElementById('a3').setAttribute('data-value', a[2])
document.getElementById('a4').setAttribute('data-value', a[3])
document.getElementById('a5').setAttribute('data-value', a[4])
document.getElementById('a6').setAttribute('data-value', a[5])
document.getElementById('a7').setAttribute('data-value', a[6]);

document.getElementById('b1').setAttribute('data-value', b[0])
document.getElementById('b2').setAttribute('data-value', b[1])
document.getElementById('b3').setAttribute('data-value', b[2])
document.getElementById('b4').setAttribute('data-value', b[3])
document.getElementById('b5').setAttribute('data-value', b[4])
document.getElementById('b6').setAttribute('data-value', b[5])
document.getElementById('b7').setAttribute('data-value', b[6]);
$('[data-target]').on("click", '[data-value]', function() {
  const clicked = $(this).addClass("actived");
  clicked.siblings(".actived").removeClass("actived");
  $(clicked.parent().data('target')).text(clicked.data('value'));
})

还有,请问有没有办法优化这个(这个真的很多)?也许一些脚本来实现这些..?:

    <ul class="list-group" id="a" data-target=".descr">
            <li class="list-group-item" id="a1">
<span>
<?php
    echo print_r($tempa[0]["name"], true);
    ?>
</span>
             </li>
<li class="list-group-item" id="a2">
<span>
<?php
    echo print_r($tempa[1]["name"], true);
    ?>
</span>
             </li>
<li class="list-group-item" id="a3">
<span>
<?php
    echo print_r($tempa[2]["name"], true);
    ?>
</span>
           </li>
</ul>

您想使用循环:

const a = ['val0', 'val1', 'val2', 'val3', 'val4', 'val5', 'val6']

for (const i in a) {
    document.getElementById('a' + i).setAttribute('data-value', a[i])
}

此外,如果您需要遍历多个数组,您可以创建简单的函数来使您的代码更简洁:

function setDataValue(id, value) {
    document.getElementById(id).setAttribute('data-value', value)
}

const a = ['val0', 'val1', 'val2', 'val3', 'val4', 'val5', 'val6']

for (const i in a) {
    setDataValue('a' + i, a[i])
}

在您的 PHP 代码中,您需要以相同的方式进行:

<?php foreach ($tempa as $key => $value): ?>
    <li class="list-group-item" id="a<?php echo $key + 1; ?>">
        <span>
        <?php
            echo $value["name"];
        ?>
        </span>
    </li>
<?php endforeach; ?>