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

我是 JS 的新手,不明白do..while等等是如何在这里工作的。我该如何优化这段代码?我正在做的事情是否正确(在每个带有 id 的元素内a[...]设置变量?我在里面有一个with , 。我正在做的是将 data-value 设置为 value 以替换 data-target (其他文本元素)数据值。b[...]a1-7list 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>


一只斗牛犬
浏览 59回答 1
1回答

MMTTMM

你想使用循环:const a = ['val0', 'val1', 'val2', 'val3', 'val4', 'val5', 'val6']for (const i in a) {&nbsp; &nbsp; document.getElementById('a' + i).setAttribute('data-value', a[i])}此外,如果您需要迭代多个数组,您可以创建简单的函数以使代码更简洁:function setDataValue(id, value) {&nbsp; &nbsp; document.getElementById(id).setAttribute('data-value', value)}const a = ['val0', 'val1', 'val2', 'val3', 'val4', 'val5', 'val6']for (const i in a) {&nbsp; &nbsp; setDataValue('a' + i, a[i])}在 PHP 代码中,您需要以相同的方式执行此操作:<?php foreach ($tempa as $key => $value): ?>&nbsp; &nbsp; <li class="list-group-item" id="a<?php echo $key + 1; ?>">&nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; <?php&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $value["name"];&nbsp; &nbsp; &nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; </li><?php endforeach; ?>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript