我有一個包含按鈕的 html 表單。此按鈕在 js 檔案中附加了一個 .click() 事件。這作業正常,直到我使用 jquery .html() 將我的主頁內容替換為表單內容。表單顯示在頁面上,但單擊按鈕不再觸發事件。我想知道這是為什么?下面的代碼...
HTML:
<body>
<div id="mainContent">
<!-- Visible page content will show here -->
</div>
<div id="otherScreens">
<form id="loginForm">
<label for="email">Email</label>
<input type="text" id="email" spellcheck="false">
<label for="password">Password</label>
<input type="password" id="password">
<button type="submit" id="signInBtn">Sign In</button>
<ul id="signInMessages"></ul>
</form>
</div>
CSS:
#otherScreens {
display: none;
}
js:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
});
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
}
我測驗了將 .click() 事件更改為目標 #mainContent 并且它在點擊網頁上 div 內的任意位置時觸發,正如預期的那樣。所以我不太確定表單按鈕發生了什么?
(似乎與建議的重復 Q 無關)
uj5u.com熱心網友回復:
只需將您的點擊功能放在 document.ready(function()
請檢查下面的完整 jQuery 代碼并將其替換為您當前的代碼:
const mainContentArea = $(document).find('#mainContent');
let onPageContent = $(document).find('#loginForm').html();
$(document).ready(function () {
mainContentArea.html(onPageContent);
$('#signInBtn').click(function (event) {
event.preventDefault();
console.log("Hello world!");
});
});
謝謝。
uj5u.com熱心網友回復:
這是非常合乎邏輯的(并且可以解釋)。您創建一個物件,將事件連接到該物件 - 然后用類似的物件替換該物件,您希望事件神奇地連接起來。這不會發生。
每次動態添加(洗掉、替換等)具有系結到該元素的事件的元素時,您需要 DOM 了解該事件。即便如此,您甚至可能最終將多個事件連接到同一元素。
所以讓我們說(作為例子)。
function replaceElement(htmlContent) {
$('.mybutton').off('click'); // drop the event handler
$('#mainContent').html(htmlContent); // replace content
// add event handler
$('.mybutton').click(function() {
console.log('yup, working again');
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/536705.html
上一篇:基于全計數的按鈕去抖動電路:
下一篇:僅在樣式中輸入鍵的WPF按下狀態
