使用jQuery进行顺序点击

时间:2011-09-07 16:13:13

标签: jquery

我希望能够点击一个按钮作为切换,用于布尔值。

当此值为true时,我希望能够单击页面上的任意位置并捕获所单击元素的父div的ID。

切换很简单,但我不知道如何做第二部分。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分: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'));
   }
}

答案 1 :(得分: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/

答案 2 :(得分:0)

您可以使用方法中的事件绑定正文上的click-event并查看event.target:

$(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...
        });
    });
});

类似的东西?