如何在textarea的onFocusOut之前调用按钮的onclick?

时间:2017-08-10 22:41:13

标签: javascript html5 events

所以我有这个包含textarea和button的td元素。当textarea聚焦时,按钮显示并保持隐藏状态。

问题是当我按下按钮时,我应该删除td元素的父元素,但是在按钮的onclick事件处理程序触发之前,我失去了textarea的焦点并且按钮被隐藏了。

以下是要素:

<td>
    <textarea oninput='textHeight(this)' onfocus='onFocus(this)' onfocusout='onFocusOut(this)'></textarea>
    <button onclick='deleteNote(this)'>X</button>
</td>

JavaScript的:

onFocus = (textarea) => {
    textarea.parentElement.querySelector("button").style.display = "inline";
}
onFocusOut = (textarea) => {
    textarea.parentElement.querySelector("button").style.display = "none";
}
deleteNote = (btn) => {
    btn.parentElement.parentElement.remove();
}

2 个答案:

答案 0 :(得分:2)

我想出了如何获得理想的结果。通过使用@Test public void testExecution() throws IOException { System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe"); // Add options to Google Chrome. The window-size is important for responsive sites ChromeOptions options = new ChromeOptions(); options.addArguments("--user-data-dir=C://Users/Evan/Downloads/Profile8Aug17"); options.addArguments("headless"); options.addArguments("window-size=1200x600"); WebDriver driver = new ChromeDriver(options); driver.get("http://seleniumhq.org"); // a guarantee that the test was really executed assertTrue(driver.findElement(By.id("q")).isDisplayed()); driver.quit(); } 事件属性focusout,我们可以有条件地允许relatedTarget在我们点击它时不被隐藏。

我改变了你的代码:

  1. button内联textarea属性中,我们必须将onfocusout属性传递给您的函数,以便我们捕获window.event事件。

  2. 我们需要访问您的函数中的focusout事件,因此我们也将其包括在内:

  3. focusout

    onFocusOut = (textarea, event) => {
    onFocus = (textarea) => {
        textarea.parentElement.querySelector("button").style.display = "inline";
    }
    onFocusOut = (textarea, event) => {
        /* this was added to show the button if it's being clicked on*/
    	if(event.relatedTarget != null){
      	if(event.relatedTarget.tagName == 'BUTTON'){
      	return
      	}
      }
    	textarea.parentElement.querySelector("button").style.display = "none";
    }
    deleteNote = (btn) => {
        btn.parentElement.parentElement.remove();
    }

答案 1 :(得分:-1)

当textarea不为空时你不隐藏按钮怎么办?

onFocusOut = (textarea) => {
    if (textarea.value === "")
        textarea.parentElement.querySelector("button").style.display = "none";
}