在 JQuery/Javascript 中设置和使用动态创建变量的属性

Setting and using attribute of dynamically created variable in JQuery/Javascript

本文关键字:动态 创建 变量 属性 JQuery Javascript 设置      更新时间:2023-09-26

我有一些javascript/JQuery,它允许我在HTML有序列表中创建一个新条目。这工作正常。但是现在我尝试将每个条目设置为具有等于变量"id"值的id,以便我可以识别一个条目并从javascript数组中删除其id

有人告诉我我不能使用 setAttribute 或 defineProperty,所以我不知道该怎么办!我包括我的两个尝试来展示我想要实现的目标:

var idList = []; //array of entry ids
$(function (){
    $("#click-me").click(function (e){
        e.preventDefault();
        i++;
        var list = $("#list"); //works fine
        var name = $("#colleague-select option:selected").text(); //works fine
        var id = $("#colleague-select").val(); //works fine
        var remove = "<button type='button' class='remove-me'> X </button>"; //works fine
        var entry = "<li>" + name + remove+ "</li>"; //works fine

        //entry.setAttribute("id", id); //doesn't work
        //or
        Object.defineProperty(entry, 'id', {
            get: function(){return id;},
            set: function(value) {id = value;}
        });

        list.append(entry); //adds entry to HTML element 'list'

        idList.push(id); //adds id to array which should be the same as entry's id
        return false;
    });
});

$(document).on('click', ".remove-me", function(){
    var entry = $(this).parent();
    entry.remove();
    var id = entry.attr("id"); //gets value of attribute "id". How will this need to be changed?
    var index = idList.indexOf(id); //finds the index number of id within array
    idList.splice(index,1); //removes id from array
});

有关如何执行此操作的帮助将不胜感激,谢谢

条目是一个 html 字符串而不是 dom 节点,你可以从中创建一个 jQuery 对象,然后添加属性或只是在字符串中添加 id

var entry = $("<li>" + name + remove+ "</li>").attr('id', id); //works fine

var entry = "<li id='""+id+"'">" + name + remove+ "</li>"; //works fine

.remove-me上的单击事件不起作用,因为您正在调用entry.remove(),然后entry.attr("id")。此时,入口元素已被删除,因此您无法获取 id。

entry.remove()移到 entry.attr("id") 下方。