2009-07-27 23 views
23

我在选择和过滤div内的元素时遇到了问题。jQuery选择和过滤div内的元素

HTML:

<div id="wrapper"> 
    <input type="text" value="you can edit me"> 
    <input type="button" value="click me"> 
</div> 

的jQuery:

$("#wrapper").children().click(function() { 
    alert("hi there"); 
}); 

问题是我得到警告我点击的div里的任何东西,每次。
但我的要求是只有当用户点击按钮时才会发出警报。
我知道,过滤jQuery中的元素使用:button

这是我曾尝试:

$("#wrapper").children(":button").click(function() { 
    alert("hi there"); 
}); 

$("#wrapper").children().filter(":button").click(function() { 
    alert("hi there"); 
}); 

它没有工作

任何人都知道这个怎么做?

+9

@Erwin - 为了将来的参考,避免在发布这样的问题时检查“社区Wiki”复选框。这是一个有效的编程问题,用户应该从中获得代表权 – 2009-07-27 17:28:35

回答

42
$("#wrapper input[type=button]").click(function() { 
    alert("hi there"); 
}); 
1

使用ID为一个特定的按钮 -

<div id="wrapper"> 
    <input type="text" value="you can edit me"> 
    <input type="button" id='btnMyButton' value="click me"> 
    <input type="button" class='btnClass' id='btnMyButton2' value="click me 2"> 
<input type="button" class='btnClass' id='btnMyButton3' value="click me 3"> 
</div> 

$('#btnMyButton').click(function(){ 
alert("hi there"); 
}); 

对于在div的所有按钮,请按照约翰的回答。使用类的一些buttons-

$('.btnClass').click(function(){ 
    alert("all class"); 
}); 

顺便说一句,我喜欢把我所有的jQuery函数准备函数内部喜欢 -

$(document).ready(function(){   

}); 
0

如何

$("#wrapper :button").click(function() { alert("I love Imogen Poots"); });

this

0

试试这个:

$("#wrapper > input[type=button]").click(function() { 
    alert("hi there"); 
});