2011-09-07 77 views
1

我希望能夠點擊一個按鈕,這個按鈕用作布爾值的切換鍵。使用jQuery連續點擊

當此值爲true時,我希望能夠單擊頁面上的任意位置並捕獲單擊元素的父div的ID。

切換很簡單,但我不知道如何做第二部分。

非常感謝您的幫助。

回答

1

試試這個

var booleanValue = false; 
$("button").click(function(){ 
    booleanValue = !booleanValue; 
}); 

$(document).click(function(e) 
{ 
    if(booleanValue){ 
     //If the parent element of the element clicked(e.target) is not a div then 
     //closest will make sure to find the nearest div 
     alert($(e.target).parent().closest('div').attr('id')); 
    } 
} 
0

提高對Rionmonster的解決方案:

var getIdBoolean = true; 
$("body").click(function(e) { 
    if (getIdBoolean) 
     $target = $(e.target); 
     alert($target.parent().attr("id")); 
} 

閱讀全部內容:http://api.jquery.com/event.target/

0

你可以只在身上綁定點擊事件在A事件方法和照顧事件。目標:

$(function() { 
    var toggle = false; 
    var button = $("#toggleButton").click(function() { 
     toggle = !toggle; 

     $("body")[toggle ? 'bind' : 'unbind']("click.parentId", function(function(e) { 
      var target = $(e.target); 
      //Your what you want to do with your target... 
     }); 
    }); 
}); 

這樣的事情?