简体   繁体   English

使用jquery使div可单击并运行函数

[英]Using jquery to make a div clickable and to run a function

So i want to execute code when i click on a div. 所以我想在单击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时调用此函数

 <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 我转到HTML文档并执行此操作

<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? 为什么在html doc中使用它会起作用,而当我尝试使用jquery使它可点击时却不能使用?

The main issue is that you need to bind your click event after the rest of the DOM has loaded 主要问题是,在其余DOM加载 ,您需要绑定click事件

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

You can see a live example here 您可以在此处看到一个实时示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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