Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
动态创建的列表项可拖动JavaScript_Javascript_List_Draggable - Fatal编程技术网

动态创建的列表项可拖动JavaScript

动态创建的列表项可拖动JavaScript,javascript,list,draggable,Javascript,List,Draggable,我正在动态填充一份参议员名单,按政治派别划分。那部分有效。我需要使每个列表项都可以拖动。我不能让它工作 我试过这个: document.getElementById(name).setAttribute('draggable'); 在我的列表循环中,但我真的不知道这是否是正确的方法 senatorList.forEach(({name, party}) => { let itemEl = document.createElement('li'); itemEl.textC

我正在动态填充一份参议员名单,按政治派别划分。那部分有效。我需要使每个列表项都可以拖动。我不能让它工作

我试过这个:

document.getElementById(name).setAttribute('draggable');
在我的列表循环中,但我真的不知道这是否是正确的方法

senatorList.forEach(({name, party}) => {
    let itemEl = document.createElement('li');
    itemEl.textContent = name;
    let listId = party === 'Democrat' ? '#democrats' : '#republicans';
    let listEl = document.querySelector(listId);
    document.getElementById(name).setAttribute('draggable');
    listEl.appendChild(itemEl);
  });

您的代码包含两个错误:

  • setAttribute
    需要两个参数:
    attribute
    value
  • 在将
    itemEl
    添加到文档之前,您调用了
    document.getElementById(name)
  • 如果我正确理解了您的意图,代码应该类似于:

    const senatorList=[{
    名称:“senator1”,
    政党:“民主党”
    },
    {
    姓名:“senator2”,
    政党:“民主党”
    },
    {
    名称:“senator3”,
    政党:“共和党”
    },
    ];
    福雷赫参议员(({
    名称
    聚会
    }) => {
    让itemEl=document.createElement('li');
    itemEl.textContent=名称;
    让listId=party==‘民主党人’?‘民主党人’:‘共和党人’;
    让listEl=document.querySelector(listId);
    setAttribute('draggable','true');
    附加子项列表(itemEl);
    });
    
    ooohoh。好啊非常感谢。