简体   繁体   English

如何存储参考 DOM 元素以备后用

[英]How to store a reference DOM element for later use

I'm on a website, I click on any element and manipulate it我在一个网站上,我点击任何元素并操纵它

document.addEventListener('click', function(e){
  e.target.innerHTML = `<span style="background: red">${e.target.innerText}</span>`
})

How can I store a reference to the element I clicked on?如何存储对我单击的元素的引用?

I want to store a reference to the database so that when the page is reloaded, that exact same element is wrapped in a span tag.我想存储对数据库的引用,以便在重新加载页面时,完全相同的元素包含在 span 标记中。

Not thoroughly tested, but an alternative to the code in Build the querySelector string value of any given node in the DOM未经过彻底测试,但可以替代构建 DOM 中任何给定节点的 querySelector 字符串值中的代码

Note: that code assumes well written HTML, ie unique ID's - unfortunately, the web is full of rubbish pages that have non-unique ID's, therefore that code will fail注意:该代码假定 HTML 编写良好,即唯一 ID - 不幸的是,网络上充满了具有非唯一 ID 的垃圾页面,因此该代码将失败

The result may well be a longer selector than the above code, but it seems to work - I've yet to break it :p结果很可能是比上面的代码更长的选择器,但它似乎有效 - 我还没有打破它:p

function getCSSPath(el) {
    const fullPath = [];
    const fn = el => {
        let tagName = el.tagName.toLowerCase();
        let elPath = '';
        if (el.id) {
            elPath += '#' + el.id;
        }
        if (el.classList.length) {
            elPath += '.' + [...el.classList].join('.');
        }
        if (el.parentElement) {
            if (el.previousElementSibling || el.nextElementSibling) {
                let nthChild = 1;
                for (let e = el.previousElementSibling; e; e = e.previousElementSibling, nthChild++);
                tagName += `:nth-child(${nthChild})`;
            }
            fn(el.parentElement);
        }
        fullPath.push(tagName + elPath);
    };
    fn(el);
    return fullPath.join('>');
}

I think this is better version of above though:我认为这是上面更好的版本:

function getCSSPath(el) {
    let elPath = el.tagName.toLowerCase();
    if (el.parentElement && (el.previousElementSibling || el.nextElementSibling)) {
        let nthChild = 1;
        for (let e = el.previousElementSibling; e; e = e.previousElementSibling, nthChild++);
        elPath += `:nth-child(${nthChild})`;
    }
    if (el.id) {
        elPath += '#' + el.id;
    }
    if (el.classList.length) {
        elPath += '.' + [...el.classList].join('.');
    }
    return (el.parentElement ? getCSSPath(el.parentElement) + '>' : '') + elPath;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM