2017-06-19 42 views
-1

我得到一個錯誤與此代碼元素添加類具有類名的TreeView

$(this + '.treeview').addClass('active'); 

的錯誤是

Uncaught Error: Syntax error, unrecognized expression: [object HTMLLIElement].treeview

如何糾正?

+0

'this'在上述背景下是一個DOM元素,你」重新嘗試將它連接到一個不起作用的字符串。 '$'構造函數將使用DOM元素,選擇器(字符串),但不能同時使用兩者。你試圖將兩者結合在一起的意圖是什麼? – FuriousD

+0

我有li元素作爲子菜單元素li的主菜單,當子菜單被點擊時,主菜單也被點擊,因爲子菜單在主菜單元素中。問題是將主菜單設置爲活動, 但是,然後我把stopPropagation放在子菜單中,以避免這種情況。 – Aidin

回答

0

您連接了一個對象和一個字符串。如果你想要做的就是找到了this代表的DOM節點的孩子,你首先需要創建一個jQuery實例:

$(this) 

,然後使用api選擇匹配類,孩子們:

$(this).children('.treeview')... 

但是,如果你正在尋找任何後代,你會使用.find()

$(this).find('.treeview')... 

或者你可以使用簡寫形式:

$('.treeview', this)... 
+0

這是工作...使用$(this).find('。treeview') – Aidin

0

我終於用@zzzzBov答案

這裏解決我的問題是完整的代碼

$('.dinz-submenu').click(function (e) { 
    e.stopPropagation(); 
}); 

$('.sidebar-menu li').click(function (e) { 
    if ($(this).hasClass('treeview')) { 
     $('.sidebar-menu li ').removeClass('active'); 
     $('.treeview-menu').slideUp(); 

     if(!$(this).find('.treeview-menu').is(':visible')){ 
      $(this).children('.treeview-menu').slideDown(); 
     } 
     $(this).addClass('active'); 

     return false; 
    } else { 
     if ($(this).hasClass('dinz-submenu')) { 
      $('.treeview-menu li ').removeClass('active'); 
     } else { 
      $('.treeview-menu').slideUp(); 
      $('.sidebar-menu li ').removeClass('active'); 
     } 
    } 
}); 
相關問題