簡體   English   中英

是否有一種簡單的方法來撤消點擊事件?

[英]Is there a simple method to undo a click event?

我正在學習基本的javascript事件,並且想知道如何撤消click事件。

我有一個簡單的事件,可以使用changeText方法更改文本。

那只是我不想做的一半。 由於用戶體驗很重要,因此我希望當用戶單擊頁面上的任何位置時都可以取消此事件。

因此,基本上,在用戶單擊按鈕並更改了文本之后,他們應該能夠在頁面上的任意位置單擊,從而使文本返回到其默認的“我將更改”。

 const changeText = () => { const p = document.querySelector('p'); p.textContent = "I changed because of an event listener."; } // Listen for click event const button = document.querySelector('button'); button.addEventListener('click', changeText); 
 <button>Click me</button> <p>I will change.</p> 

您可以將eventListener附加到文檔:

document.addEventListener('click', changeTextBack)


changeTextback (event) {
// use event target to make sure he is not clicking on button
// use same methods as in changeText method to target element and alter text
}

該文檔代表整個頁面。 您也可以將其附加到窗口。 https://developer.mozilla.org/zh-CN/docs/Web/API/Document https://developer.mozilla.org/nl/docs/Web/API/Window

這個有幫助嗎?

因此,您只需要另一個click事件,但要在另一個對象上。 在HTML中,您必須創建某種容器,然后:

const changeTextBack = () => {
    const p = document.querySelector('p');

    p.textContent = "I will change.";
}

// Listen for click event
const buttonContainer = document.querySelector('button-container');
buttonContainer.addEventListener('click', changeTextBack);

您可以在文檔上綁定事件,並將默認文本全局存儲在某處。 請參閱以下解決方案:

 let obj = {}; // object to store the def text of "p" const changeText = (event) => { // pass the event object here event.stopPropagation(); // stop the event to propagate back to parent const p = document.querySelector('p'); if (event.target.tagName === "BUTTON") { // if clicked item is button if (!obj['p']) { obj['p'] = p.textContent; // store the def text in obj } p.textContent = "I changed because of an event listener."; // change the text } else { // otherwise p.textContent = obj.p; // change back the def text } } // Listen for click event const button = document.querySelector('button'); button.addEventListener('click', changeText); document.addEventListener('click', changeText); 
 <button>Click me</button> <p>I will change.</p> 

您可以添加另一個函數revertText來撤消更改,並在單擊document時調用它。 但是,如果執行此操作,則也將在單擊按鈕時觸發它。 因此,為了僅在單擊按鈕時觸發該按鈕事件,請使用e.stopPropagation()來停止執行document單擊事件。

請參見下面的工作示例:

 const changeText = e => { // Pass event (e) argument into function e.stopPropagation(); // Stop the document click event from running const p = document.querySelector('p'); p.textContent = "I changed because of an event listener."; } const revertText = () => { const p = document.querySelector('p'); p.textContent = "I will change"; } // Listen for click event const button = document.querySelector('button'); button.addEventListener('click', changeText); document.addEventListener('click', revertText) // Add second event listener on the document 
 <button>Click me</button> <p>I will change.</p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM