一个div内部jQuery的选择和过滤元件(jQuery selecting and filteri

2019-07-30 21:38发布

我有选择并过滤一个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");
});

它没有工作

有人知道怎么做吗?

Answer 1:

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


Answer 2:

使用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(){        

});


Answer 3:

怎么样

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

见这



Answer 4:

试试这个:

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


文章来源: jQuery selecting and filtering elements inside a div