简体   繁体   中英

jQuery - hide, show, add/remove class on dynamically added elements

So I'm stuck with this project where I have dynamically injected some external HTML into my main document and I want to reference elements that are inside the external document. I'm aware of the on() method, which I have used and it works, but the actions inside the function are not working at all.

For some reference, the injected HTML code is a simple button which should hide another element when clicked. Like so:

<! –– MAIN HTML––>
...
<div class="main">
</div>
...

<! –– INJECTED HTML (content_home.html)––>

<button id="button">Button</button>
<div id="stuff">Stuff</div>

I wrote this in my JavaScript code:

$(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.");
})
}

The thing is, the console displays the desired message when clicking the button, so I know something is working, but that's it. hide() , show() don't work at all. The console doesn't even throw an error.

What am I doing wrong? Do I need to add a $(this) of sorts? I've been browsing the inte.net looking for the answer, to no avail.

Thank you

your code is working correctly. maybe you have not linked jquery script correctly.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM