简体   繁体   中英

Using jquery to make a div clickable and to run a function

So i want to execute code when i click on a div.

So I have a function

function froth(){$("#area").load("test.html #enquiry1");}

I want to call this function when I click a div

 <div id="t1">Test</div>

So I try and use this code

 $('#t1').click(function(){
  froth();
  });

Nope it doesnt work.

BUT

I go to the HTML document and do this

<div id="t1" onclick="froth()">Test</div>

AND IT works perfectly .

So my question is, what am i doing wrong here? Why would it work when in the html doc and not work when i try and make it clickable with jquery?

The main issue is that you need to bind your click event after the rest of the DOM has loaded

$(document).ready(function() {
    $('#t1').on('click', function(){
        froth();
    });
});

You can see a live example here

$(document).on('click', '#t1', function() { 
 froth();
});

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