JavaScript在动态生成的元素中设置onclick

问题描述 投票:0回答:1

我有一个对象,我想循环创建元素。每个元素都应该有一个onclick来更改另一个元素的文本(用于动态生成的下拉列表)。

    const orders = {
        INDEX: 'index',
        REVERSE_INDEX: 'reverse index',
        RANDOM: 'random',
        SELECTION: 'selection order',
        REVERSE_SELECTION: 'reverse selection order',
        CURRENT_ORDER: 'current start order',
        REVERSE_CURRENT_ORDER: 'reverse current start order',
        ALPHABETICAL: 'alphabetical',
        REVERSE_ALPHABETICAL: 'reverse alphabetical'
    };

    var ddc = document.getElementById("orderDropDownContent");

    for (var key in orders) {
        var ddMenuItem = document.createElement("p");
        ddMenuItem.className = "dropdown-item";
        ddMenuItem.onclick = function() { 
            document.getElementById("orderDropDown").innerText = orders[key];
        };
        ddMenuItem.innerText = orders[key];
        ddc.appendChild(ddMenuItem);
    }

HTML只是

<div class="dropdown">
    <div id="orderDropDown" value="index" class="dropbtn">index</div>
    <div id="orderDropDownContent" class="dropdown-content">
    </div>
</div>

内部文本适用于每个元素,并且每个元素都有一个onclick,但是问题是onclick函数从创建时起就没有使用orders[key]value,而是使用< [表达式 orders[key]等于对象“反向字母顺序”中的最后一个值。如何在创建函数时使用字符串值创建函数。

我尝试添加行

var theText = '' + orders[key];

但是那没用。

我觉得以前可能已经问过这个,但是我找不到重复的。

javascript dom onclick
1个回答
0
投票
Var的作用域是最接近的函数,因此,当您遍历for循环并添加事件侦听器时,在实际调用该函数时(稍后),key始终是循环遍历时的最后一个值它。解决此问题的几种方法,最简单的方法是使用let进行块作用域化而不是var。最佳实践是在可能的情况下始终使用const,并在其他地方使用,并避免使用var。

JavaScript closure inside loops – simple practical example

© www.soinside.com 2019 - 2024. All rights reserved.