获取给定元素的特定父元素(在Javascript中)

时间:2018-02-09 14:12:13

标签: javascript dom javascript-events drag-and-drop

我试图做可拖动的待办事项列表,我遇到了这个问题。 这是HTML:

<div class="to-do-element editing" draggable="true">
    <div class="text-wrapper">
        <span><span class="index">1</span>.</span>
        <span class="to-do-text"></span>
        <input type="text" class="to-do-input" placeholder="Click to add text."/>
    </div>
    <div class="buttons">
        <button type="button" class="save-button icon-checkmark" data-button="save"></button>
        <button type="button" class="edit-button icon-pencil" data-button="edit"></button>
        <button type="button" class="delete-button icon-cross" data-button="delete"></button>
        <button type="button" class="move-up-button icon-arrow-up2" data-button="move-up"></span></button>
        <button type="button" class="move-down-button icon-arrow-down2" data-button="move-down"></button>
        <button type="button" class="cross-out-button icon-strikethrough" data-button="cross-out"></button>
        <button type="button" class="uncross-out-button icon-undo" data-button="uncross-out"></button>
    </div>
</div>

和JS:

thisDiv.addEventListener('dragover', (e) => {
    e.preventDefault();
});

thisDiv.addEventListener('dragstart', (e) => {
    console.log(e.target.querySelector('.index').innerText);
    e.dataTransfer.setData('text', e.target.querySelector('.index').innerText);;
});

thisDiv.addEventListener('drop', (e) => {
    console.log(document.querySelector('.to-do-element:nth-of-type(' + e.dataTransfer.getData('text') + ')'));
    console.log(e);
    document.querySelector('#to-do-list').insertBefore(document.querySelector('.to-do-element:nth-of-type(' + e.dataTransfer.getData('text') + ')'), e.target);
})

事情是e.target太具体了,我想知道我指的是哪个,但如果我指的是完全指向跨度,它会让我回到跨度等等。我想过使用像.parentElement这样的东西,但没有帮助。我可以循环.path并进行比较,但我正在寻找更好的方法。

0 个答案:

没有答案