[英]jQuery - hide, show, add/remove class on dynamically added elements
所以我堅持這個項目,我動態地將一些外部 HTML 注入到我的主文檔中,我想引用外部文檔中的元素。 我知道我使用過的on()
方法並且它有效,但是 function 中的操作根本不起作用。
作為參考,注入的 HTML 代碼是一個簡單的按鈕,單擊時應該隱藏另一個元素。 像這樣:
<! –– MAIN HTML––>
...
<div class="main">
</div>
...
<! –– INJECTED HTML (content_home.html)––>
<button id="button">Button</button>
<div id="stuff">Stuff</div>
我在我的 JavaScript 代碼中寫了這個:
$(document).ready(function () {
const main = $(".main");
function loadHome() {
fetch('html/content_home.html').then(function (response) {
return response.text();
}).then(function (html) {
main.append(html);
}).catch(function (error) {
console.warn('Something went wrong.', error);
});
}
loadHome();
const doc = $(document);
doc.on("click", "#button", function() {
$('#stuff').hide();
console.log("You clicked on the button.");
})
}
問題是,單擊按鈕時控制台會顯示所需的消息,所以我知道某些東西正在工作,僅此而已。 hide()
, show()
根本不起作用。 控制台甚至不會拋出錯誤。
我究竟做錯了什么? 我需要添加 $(this) 嗎? 我一直在瀏覽 inte.net 尋找答案,但無濟於事。
謝謝
您的代碼工作正常。 也許您沒有正確鏈接 jquery 腳本。
const doc = $(document); doc.on("click", "#button", function() { $('#stuff').toggle(); console.log("You clicked on the button."); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="button">Button</button> <div id="stuff">Stuff</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.