【问题标题】:jQuery selecting and filtering elements inside a divjQuery 选择和过滤 div 中的元素
【发布时间】:2010-11-14 10:31:35
【问题描述】:

我在选择和过滤 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");
});

没用

有人知道怎么做吗?

【问题讨论】:

  • @Erwin - 以供将来参考,在发布此类问题时避免选中“社区 Wiki”复选框。这是一个有效的编程问题,用户应该从中获得代表

标签: javascript jquery filter css-selectors


【解决方案1】:
$("#wrapper input[type=button]").click(function() {
    alert("hi there");
});

【讨论】:

    【解决方案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 中的所有按钮,请遵循 John 的回答。对一些按钮使用类-

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

    顺便说一句,我喜欢把我所有的 jquery 函数放在准备好的函数中,比如-

    $(document).ready(function(){        
    
    });
    

    【讨论】:

      【解决方案3】:

      怎么样

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

      this

      【讨论】:

        【解决方案4】:

        试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-30
          • 1970-01-01
          • 1970-01-01
          • 2017-04-23
          • 2021-10-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多