简体   繁体   中英

How do I use jquery for div's onclick event?

I have several div's on my page. See example http://jsfiddle.net/AYRh6/26/ When I'm trying to transfer this code to my asp.net mvc3 project it looks like:

<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script type="text/javascript">  
        $('.tab').click(function() {
        $(this).addClass('active').siblings().removeClass('active');
        })​;
    </script>
</head>
<body>
<div class="main">
        <div class="tab" style="float:right;">Tab 3</div>
        <div class="tab" style="float:right;">Tab 2</div>
        <div class="tab active" style="float:right;">Tab 1</div>
    </div>
</body>
</html>

CSS:

.main{
    width:325px;
}
div.tab {
    background: white;
    width: 100px;
    border: 1px solid grey;
    padding-left:5px;
}
div.tab.active {
    background: blue;
}
div.tab:hover {
    background: aqua;
}

As you can see javascript is located at the header of html page. It doesn't work for me. I was trying to set this script for onclick event like:

<div class="tab" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 3</div>
            <div class="tab" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 2</div>
            <div class="tab active" style="float:right;" onclick="$(this).addClass('active').siblings().removeClass('active');">Tab 1</div>

It's work fine! What I'm doing wrong when this script located at the header?

The Javascript code is executed immediately but the elements that you want to attach the handlers to haven't been put into the DOM yet. You can use .ready in jQuery or put your script at the bottom of the document:

<script type="text/javascript">  
    $(document).ready(function(){
            $('.tab').click(function() {
            $(this).addClass('active').siblings().removeClass('active');
        }
     })​;
</script>

If you use a debugger and set a breakpoint at $('.tab').click in your code you'll notice that $('.tab') returns an empty array of elements.

If you take a look to your link you will see that you choose the option to execute the script on DOM ready. You have to do the same on your website.

jQuery(document).ready(function() {
    $('.tab').click(function() {
        $(this).addClass('active').siblings().removeClass('active');
    })​;

});

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