2016-03-06 72 views
0

我有這樣的腳本:如何檢查它被點擊一個div的孩子之一?

$('body').click(function(evt){ 
    var all_childs=$("#menu-js").find('*'); 
    console.log(all_childs); 
    if(evt.target.id == "menu-js"){ //here should change condition 
     console.log(evt.target.id); 
     return; 
    }else{ 
     if($('#menu-left').is(':visible')) 
     { 
      $("#menu-left").hide(); 
     }else{ 
      if(evt.target.id == "cake") { 
       $("#menu-left").show(); 
      } 
     } 
    } 
}); 

我要的是檢查它是否被點擊的"all_child"

的要素之一,我把鏈接到我的網站,以更好地檢查代碼

link

我該如何處理這種情況?

提前致謝!

編輯:

sample

代碼HTML:

<div id="menu-js"> 
    <ul id="menu-left"> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    </ul> 
</div> 

<button id="cake">SHOW MENU</button> 

回答

0

檢查它像這樣(更新按照您的要求)

var $target = $(evt.target || evt.srcElement); 
// check if the current target has a parent with id 'menu-js' 
if ($target.parents("#menu-js").length > 0) { 
    if ($('#menu-left').is(':visible')) { 
    $("#menu-left").hide(); 
    } 
} else if (evt.target.id == "cake") { 
    $("#menu-left").show(); 
} 
+0

我會做出一個例子,這裏的鏈接後 –

+0

當然知道,但我認爲你可以通過這個代碼,你的問題問實現。 –

+0

你能試着編輯我的樣品嗎? http://codepen.io/anon/pen/YqyoWY –

0

這是完全可以作爲你自找的 !

這裏是鏈接到:JsFiddle

$('body').click(function(e) { 

    var target = $(e.target); 
     console.log(target.context); 
     console.log(target.is(':visible')) 

    if(target.context.id == "menu-js"){ //here should change condition 
       alert(target.context.id); 
    }else{ 
        if($('#menu-left').is(':visible')){ 
      $("#menu-left").hide(); 
      }else{ 
      if(target.context.id == "cake") { 
       $("#menu-left").show(); 
      } 
      } 
     } 
}); 
相關問題