首页 > 解决方案 > 在 JavaScript DOM 中是否可以将整个按钮功能克隆到另一个?

问题描述

我的意思是是否可以将现有按钮与新创建的按钮连接起来,该按钮将用作现有按钮?

参考网站:https ://www.ninetypercent.com/products/sleeveless-gather-maxi-dress-c5?color=red

打开以上链接后,请将以下代码粘贴到浏览器控制台:

let title = document.querySelector(".product-details__name").textContent;
let price;
let oldPrice = document.querySelector(".product-details__old-price");

if (oldPrice) {
    price = oldPrice.nextSibling.textContent.trim();
} else {
    price = document.querySelector(".js-product-price").textContent;
}

let div = document.createElement("div");

let path = document.querySelector("header");
div.innerHTML = `
    <div
        id="sticky-nav"
        style="position: fixed;
               top:110px;
               display: none;
               padding: 0 10px;
               justify-content: space-between;
               align-items: center;
               background-color:#e4e4e4;
               width: 100vw;"
        class="sticky-wrapper"
    >
    <div
        style="width:80%; display: flex; justify-content: space-between; align-items:center"
        class="sticky-text-wrapper"
    >
        <p style="margin: 0;" class="sticky-text">${title}</p>
        <p style="margin: 0;" class="sticky-price">${price}</p>
    </div>
    <span style="width: 18%; display: flex; justify-content: space-around;" class="button"></span>
</div>`;

path.appendChild(div);
const sourceElement = document.querySelector(".js-product-details-submit-wrapper button");

const destination = document.querySelector(".button");

const copy = sourceElement.cloneNode(true);
destination.appendChild(copy);

window.addEventListener("scroll", () => {
    const scrollPos = window.scrollY;
    if (scrollPos > 1500) {
        document.getElementById("sticky-nav").style.display = "flex";
    } else {
        document.getElementById("sticky-nav").style.display = "none";
    }
});

我想将粘性导航按钮连接到现有的“添加到包”按钮,两个按钮的功能将是相同的。与控制相同的消息将出现在 PDP(产品详细信息页面)上,并且购物篮图标数量将增加。我怎样才能做到这一点?

标签: javascriptdom-events

解决方案


在一个按钮的单击处理程序中,您可以触发另一个按钮,如下所示(名称当然是组成的):

stickyNavBtn.onclick = () => addToBagBtn.click();

推荐阅读