这个jquery脚本有什么问题吗?

时间:2010-11-27 18:20:54

标签: javascript jquery

所以我试图在点击show hide元素上应用基本但由于某种原因它不起作用

我通过外部javascript文件使用它,并包括我的母版页中包含的最新jquery库firebug显示代码,所以我知道它捡起来

继承人试过的代码

$(document).ready(function () {
// hides the divx as soon as the DOM is ready
$('#ecom').hide();
// shows the div on clicking the noted link  
$('.eco').click(function () {
    $('#ecom').show('slow');
    return false;
});
// hides the div on clicking the noted link  
$('.eco').click(function () {
    $('#ecom').hide('fast');
    return false;
}); 
});

HTML

<h2 class="eco">Ecommerce Web Design</h2>
<div id="ecom">content</div>

我自己没有看到问题

这是我最终使用的解决方案,我想要它做什么:) 谢谢你们所有的答案

$(document).ready(function () {
$('#ecom').hide();
$('.eco').click(function () {
    $('#ecom').toggle('slow');
    return false;
});

2 个答案:

答案 0 :(得分:5)

两个处理程序将同时启动。

我认为你正在寻找.toggle()

示例: http://jsfiddle.net/patrick_dw/uuJPc/

$('.eco').toggle(function () {
    $('#ecom').show('slow');
    return false;
},function () {
    $('#ecom').hide('fast');
    return false;
});

现在它会在点击之间切换。


编辑:如果您以下面提到的@Tgr的方式使用.toggle(),则需要某种方法来区分代码中的"slow"/"fast"

这是一种方式:

示例: http://jsfiddle.net/patrick_dw/uuJPc/1/

$('#ecom').hide();
$('.eco').click(function () {
    var i = 0;
    return function() {
        $('#ecom').toggle(i++ % 2 ? 'slow' : 'fast');
        return false;
    };
}());

或者像这样:

示例: http://jsfiddle.net/patrick_dw/uuJPc/2/

$('#ecom').hide();
$('.eco').click(function () {
    var ec = $('#ecom');
    ec.toggle(ec.is(':visible') ? 'slow' : 'fast');
    return false;
});

答案 1 :(得分:3)

你可以使用toggle而不是手动完成整个事情,但这是一种捷径。如果您正在尝试学习这些内容,我建议您从头开始创建它,并且只有在您完全了解幕后发生的事情时才使用快捷方式。

$(document).ready(function(){
    // Hide ``#ecom`` on page load.
    $('#ecom').hide();
    // Attach only one click handler (yours was attaching a handler that showed
    // the div and then on that hid the div, so it was always shown, and then
    // hidden instantly, therefore canceling your intended effect.
    $('.eco').click(function(e){
        // ``preventDefault()`` is the W3 correct way to stop event propagation
        // and works cross-browser. It's a bound method on all DOM events.
        // Notice I've given my click handler function an argument ``e``. When
        // you register an event handler function, the event that causes the
        // handler function to be called is provided as the first argument handler
        // function, thus giving us ``e`` as a local reference to the event.
        e.preventDefault();
        // Use ``is()`` to compare the element against the ``:hidden`` selector.
        // This will tell us if it's hidden or not.
        if($('#ecom').is(':hidden'))
        {
            $('#ecom').show('slow');
        } else {
            $('#ecom').hide('fast');
        }
    });
});
相关问题