2012-11-09 88 views
0

我有兩個div,其他的一個內:選擇父DIV的時候,我只煥選擇兒童DIV

<div id="parent"> 
    <div id="children"> 
     Click me 
    </div> 
</div> 

當我點擊了孩子的div使用jQuery,父也被點擊了。

$(function() { 
    $("div").click(function(){ 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

我該怎麼做才能避免這種情況?這裏是我的jsfiddle:http://jsfiddle.net/gzpPB/1/

+0

爲什麼不只是針對其ID孩子的div? – j08691

+0

嘿,@GalloPinto,如果你可以選擇這個問題的答案可能會很好......謝謝! – exoboy

回答

2

最健壯的解決方案是簡單地給所有點擊接受的DIV元素一個特定的類。這樣,無論在哪裏,或者嵌套了多深,只有具有「按鈕」類的元素纔會被觸發。

NEW CODE:

<div id="parent"> 
    <div id="children" class="button"> 
     Click me 
    </div> 
</div> 


$(function() { 
    $(".button").click(function(){ 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

如果您使用jQuery 1.8或更高版本,你需要做這種方式:

$(function() { 
     $(document).on('click', ".button", function(){ 
      alert("The id of the selected item is: " + $(this).attr("id")); 
     }); 
    });​ 
2

在您選擇更具體:

$("#children") instead of $("div") 
0

Becoz你只是針對頁面上的div元素。使用e.target來定位特定的div。 也e.stopPropagation()

$(function() { 
     $("div").click(function(e){ 
      if(e.target.id == 'children'){ 
       e.stopPropagation(); 
       alert("The id of the selected item is: " + $(this).attr("id")); 
      } 
     }); 
    }); 

Check Fiddle

0

使用.stopPropagation()像:

$(function() { 
    $("div").click(function(e){ 
     e.stopPropagation(); 
     alert("The id of the selected item is: " + $(this).attr("id")); 
    }); 
});​ 

jsFiddle example

您的代碼警報兩個div的,當你cli來因爲bubbling因子ck。對孩子的點擊傳到父級,然後再次觸發laert,因爲你的jQuery的目標是所有的div,而不是特定的div。您只能通過使用$("#children")來針對只有子div。但是,您也可以使用stopPropagation()來阻止冒泡,這可以讓您的警報在單擊任何div時運行,而不僅僅是一個特定的div。