2012-10-18 34 views
0

我試圖獲得實現鑽取列表類功能。javascript代碼執行如果和其他塊

代碼運行良好,.toggle(),但我的下鑽列表項來自AJAX請求,所以我試圖在.live('click')事件中編寫基本的自定義切換。

現在的問題是代碼在ifelse塊中都正在執行。

我的JavaScript代碼如下:

$(document).ready(function(){ 
    var $drillDownListItem = $("li.listItem"); 
    var flag = 0; 

    var options = { 
     $this: "" 
    }; 

    $drillDownListItem.live('click', function() { 
     options.$this = $(this); 
     if(!$(this).children("ul").is(":visible")) 
     { 
      showChildren(options); 
     } 
     else 
     { 
      hideChildren(options); 
     } 
    }); 

    $drillDownListItem.each(function() { 
     if ($(this).children("ul").length > 0) { 
      $(this).css({ 
       "padding-bottom": "0px" 
      }); 
      $(this).children("ul").hide(); 
      $(this).children("span:first-child").css({ 
       "padding-bottom": "11px" 
      }); 
     } 
    }); 
}); 

var showChildren = function(options) { 
    if (options.$this.children("ul").length > 0) { 
     options.$this.css("background-image", "url(./images/dropDownDown.png)"); 
     options.$this.children("ul").slideDown(500); 
     //options.$this.children("span:first-child").css({"padding-bottom": "6px", "float": "left"}); 
    } 
} 
var hideChildren = function(options) { 
    if (options.$this.children("ul").length > 0) { 
     options.$this.css("background-image", "url(./images/sideArrow.png)"); 
     options.$this.children("ul").slideUp(500); 
     //options.$this.children("span:first-child").css({"padding-bottom": "6px", "float": "left"}); 
    } 
} 

不知道爲什麼發生這種情況,但在調試,

一旦if塊(showChildren())執行完畢,控制跳入else塊(hideChildren()),並將$(this)的值更改爲父項。

+0

你能告訴我們你的HTML爲它創建一個jsfiddle嗎? – KyorCode

+0

聽起來就像你有兩個嵌套的li.listitem元素。可以用'event.stopPropagation();' – Jan

回答

1

從您的描述來看,聽起來就像您的點擊事件冒泡了一樣。返回false以防止出現這種情況:

$drillDownListItem.live('click', function() { 
    options.$this = $(this); 
    if(!$(this).children("ul").is(":visible")) 
    { 
     showChildren(options); 
    } 
    else 
    { 
     hideChildren(options); 
    } 
    return false; 
}); 
+0

解決這個問題? :o –

+0

「_once if block(showChildren())執行完畢後,控制權跳轉到else塊(hideChildren())並且$(this)的**值改變爲父**。事件冒泡DOM樹 – cbayram

+0

今天回想起來,有點顯而易見的事件發生了。昨天我的頭太擁擠了。不管怎麼說,多謝拉 :) –