切换仅在双击时有效

时间:2012-10-21 02:54:04

标签: javascript jquery

当我使用onmousedown事件点击我的链接时,我必须双击它们才能切换它们。我不明白为什么会这样。

function toggleInteractContainers(x) {
//the 'x' variable represents the add friend/message container value
        if($('#'+x).is(":hidden")) {
        //if the container is hidden then we will slide it down and show it
            $('#'+x).slideToggle(400);

        } else {
            //if its not being hidden then we will hide it
            $('#'+x).hide();
        }
        //this just means we have to hide all the containers
        $('.interactContainers').hide();
}

我从这个div中调用它

<div class ="interactionLinksDiv">
           <a href="#" onclick="return false" onmousedown="toggleInteractContainers('add_friend');">Add Contact</a>
</div>          
<div class ="interactContainers" id ="add_friend">
  <div align ="right"><a href="#" onclick= "return false" onmousedown = "toggleInteractContainers('add_friend')">cancel</a></div>
                Add as a contact? &nbsp;
  <a href ="#" onclick="return false" onmousedown="javascript:addAsFriend(); ">Yes</a>  
</div>

我没有收到任何令人沮丧的错误。如果我被告知为什么会发生这种情况以及我能做些什么来阻止它再次发生,我将非常感激。沿途的任何编程技巧也都很棒。

2 个答案:

答案 0 :(得分:1)

我尝试在jsFiddle中重做这个。这有点复杂,因为我们没有更多细节。

HTML:

<div class ="interactionLinksDiv">
    <a href="#" class="toggleInteractContainers" data-target="add_friend">Add Contact</a>
</div>          
<div class ="interactContainers" id ="add_friend">
  <div align ="right">
      <a href="#" class="toggleInteractContainers" data-target="add_friend">cancel</a></div>
  Add as a contact? &nbsp;
  <a href ="#" class="addAsFriend">Yes</a>  
</div>​

使用Javascript:

$(function() {

    $(document).on("click", ".toggleInteractContainers", function() {
        target_id = $(this).data("target");
        $('#' + target_id).slideToggle(400);
    });


    $(document).on("click", ".addAsFriend", function() {
        // Do something here when someone clicks on Yes 
    });

});​

http://jsfiddle.net/Kj4rK/

基本上,这里有几点说明。

  • 您正在使用jQuery,您不应该直接在DOM中使用事件(不要使用onmouseclick =“”内部标记)。您应该使用jQuery中包含的正确绑定和/或委托函数。 http://api.jquery.com/on/

  • .toggle()和.slideToggle()始终执行其状态的对立面:如果它们被隐藏,它将显示,如果它是可见的,它将隐藏。你的代码没有用,因为你有条件(如果它被隐藏,切换它 - 而不是如果它被隐藏,显示它)http://api.jquery.com/slideToggle/

答案 1 :(得分:0)

工作演示完成了少量更改:http://jsfiddle.net/FGqE7/

如果我遗漏了什么,请告诉我!

希望它适合原因:)

<强>代码

function toggleInteractContainers(x) {
    //the 'x' variable represents the add friend/message container value
    if (!$('#' + x).is(":visible")) {
        //if the container is hidden then we will slide it down and show it
        $('#' + x).slideDown(400);

    } else {
        //if its not being hidden then we will hide it
        $('#' + x).hide();
    }
    //this just means we have to hide all the containers
   // $('.interactContainers').hide();
}​