为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2023-08-10 15:47:44
我是 JS 的新手,不明白do..while等等是如何在这里工作的。我该如何优化这段代码?我正在做的事情是否正确(在每个带有 id 的元素内a[...]设置变量?我在里面有一个with , 。我正在做的是将 data-value 设置为 value 以替换 data-target (其他文本元素)数据值。b[...]a1-7list grouplist items#a1-7#b1-7document.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>
查看完整描述

1 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

你想使用循环:


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; ?>


查看完整回答
反对 回复 2023-08-10
  • 1 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信