jQuery: Why does my click event on a li element no

2019-04-22 08:35发布

问题:

I want to move the Div-element "nav", when a li-element was clicked.

I have a List in a div

<div id="nav">
    <ul>
        <li><a href="#t1">Flyer</a></li>
        <li><a href="#t2">Code</a></li>
        <li><a href="#t3">Angebot</a></li>
        <li><a href="#t4">Bilder</a></li>
    </ul>
</div>  

Why doesnt this work in jquery:

$("#nav ul li").click(function(){
    $("#nav").animate({ 
        marginLeft: "-300px",
    }, 1000 );
});

回答1:

The code works fine as you expect, view the JSFiddle.

I have a feeling your forgetting something like putting it in the jQuery DOM Ready event.

Make sure you code looks like this (inside the DOM Ready)

$(document).ready(function(){ // When the DOM is Ready, then bind the click
    $("#nav ul li").click(function(){
        $("#nav").animate({ 
            marginLeft: "-300px",
        }, 1000 );
    });
});

Make sure you have no other javascript errors on your page (If you do before this code, the code will not work), Check your console (In chrome right click > Inspect Element > console).

One of these 2 issues are causing your problems (most likely), else you will have to debug it yourself (or show us more code).



回答2:

Depending on what version of Jquery you are using this may or may not work:

$('body').on('click', '#nav ul li', function(){
    $("#nav").animate({ 
        marginLeft: "-300px",
    }, 1000 );
});

I did $('body') because if you are generating these li's dynamically then you need to bind 'delegated events' as they're called.



回答3:

It works as expected, but you have to click on the li-element. If you click on the anchor, it might break on some browsers.

Here is a better approach on this.

HTML

<div id="nav">
 <ul>
 <li><a href="#t1">Flyer</a></li>
 <li><a href="#t2">Code</a></li>
 <li><a href="#t3">Angebot</a></li>
 <li><a href="#t4">Bilder</a></li>
 </ul></div>

jQuery

(function($) {
    var nav = $('#nav');

    nav.find('a').on('click',function(e){
        e.preventDefault();
        nav.animate({ 
            marginLeft: "-300px",
        }, 1000 );
    });
})(jQuery);

And of course, fiddle: http://jsfiddle.net/dKPqJ/



回答4:

Try out this one, and i think there is no error in your code as well.

in my knowledge your code will work if you give float:left property for #nav.

if you set position then the following code will work.

$(document).ready(function(){
 $("#nav ul li").click(function()
 {
    $("#nav").animate({ 
     left: "-=300px",
    }, 1000 );
 });
});

Or try this one

$(document).ready(function(){
 $("#nav ul li").click(function()
 {
   $("#nav").animate({
       "left": "-=300px"
    },
  "slow");
 });
});