简体   繁体   中英

javascript/jquery issue while clicking

There's something going wrong with my java script code. I have a basic html page and this code

<div class="myclass" id="myid"> 
   <h3 class="myotherclass"><?php echo _("Some sentence"); ?></h3>
</div>

When I put this script :

<script type="text/javascript">
    $("div").click(function () {
        alert('hello');
    });
</script>

the click on the div tag triggers the alert message, but when I put this :

<script type="text/javascript">
    $("h3").click(function () {
        alert('hello');
    });
</script>

nothing is triggered. Could some explain this ?

You should put your code within document ready handler:

$(document).ready(function(){
   // ...
})

In fact in this case, you can use jquery's live() syntax : .live( events, handler(eventObject) ) , see here here . You can also use on() syntax .on( events [, selector] [, data] , handler(eventObject) ) because live is beginning being deprecated for the recent versions of jquery, see here here

你把代码包装在ready处理程序中了吗?

$("document").ready(function(){})

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