简体   繁体   中英

Getting a jQuery function to fire

I have a very simple jQuery function

$('#bnAddDegree').click(function () {
    alert("bnAddDegree Loaded");          
});

I have broken my site into different pieces based upon what the user clicks. If they click on a tab in the menu to load a section I call a partial_html page and load the section into the center div. If I put the code above into the main page load it will not fire. If I add an external js file and load it when the page loads it will not fire, I think because the elements are not initialized yet. If I put it into an external js page that is loaded after the partial_html is loaded it will not fire. If I put it ON the partial_html page with a tag it DOES fire. If I put a simple javascript function

function testFile() {
    alert("File Loaded");
}

In the places that the jQuery code will not fire it works fine.

Is there something special that I'm missing with jQuery?

When I load the javascrip file I use

$.getScript("js/biosketch.js")

And test it with the simple javascript file and it works fine but not the jQuery call.

You need to use delegated event handlers since you are modifying the DOM dynamically.

$(document).on('click', '#bnAddDegree', function () {
    alert("bnAddDegree Loaded");          
});

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