【问题标题】:how to determine which button has been clicked in jqueryjquery如何判断点击了哪个按钮
【发布时间】:2011-05-04 12:19:07
【问题描述】:

我正在使用 php 循环来生成多个按钮元素。使用jquery如何确定点击了哪个按钮?

<script type="text/javascript">

$(function(){

    if(button.click){
        alert(button.id);
    }

});

</script>

<?php for($x=0; $x<4; $x++){ ?>
<ul id="x">
<li><input type="button" id="<?php echo $x; ?>" value="<?php echo $x; ?>"/></li>
</ul>
<?php } ?>

【问题讨论】:

  • 您实际上并没有将 ID 属性放到输入中。
  • 我认为下面的任何答案现在都应该可以解决您的问题。

标签: jquery jquery-selectors


【解决方案1】:

标识元素最常用的方法是 id。 (Literally, id does mean "identification")

你想要的方式,应该是这样的。

$("input").click(function() { //This will attach the function to all the input elements
   alert($(this).attr('id')); //This will grab the id of the element and alert. Although $(this).id also work, I like this way.
});

但是,将绑定泛化到所有输入元素可能不是一个好主意。因此,请尝试为特定元素提供一个通用类并改用$(".yourclass")

【讨论】:

    【解决方案2】:

    好吧,如果您的代码如下所示

    $('input:button').click(function(){
       $(this); //this will always refer to the clicked button. 
                //You can use traversal to find stuff relative to this button
       var butId = $(this).attr('id'); //this will give you the ID of the clicked button
    });
    

    【讨论】:

    • +1 以获得很好的解释,这里是 test case 供任何想要的人使用。 :)
    【解决方案3】:
    <?php for($x=0; $x<4; $x++){ ?>
    <ul id="x">
    <li><input type="button" id="<?php echo $x; ?>"  value="<?php echo $x; ?>"/></li>
    </ul>
    <?php } ?>
    
    <script type="text/javascript">
        $("input").click(function() {
            clickButton(this) // this is the button element, same as alert(this.id)
        });
    
        function clickButton(button) {
            alert(button.id)
        }
    </script>
    

    编辑:每个 JS 绑定是首选

    【讨论】:

    • 不推荐使用 onclick。最好通过JS绑定
    • 更好,但您不再需要clickButton。对不起,如果我听起来像是在吹毛求疵:)
    • 好吧,当与“onclick”绑定时,我也没有需要该功能,可以写onclick="alert('this.id')"
    • 不不,我的意思是你已经定义了一个函数来处理点击事件(你的匿名函数)。你可以简单地在你的点击方法中移动alert
    • jup,我知道这一点,但是通过使用命名函数clickButton,我可以从代码中的其他位置调用该函数。当然,当涉及更多登录时,这更有意义。
    【解决方案4】:
    $(function() {
        $("input[type='button']").click(function(event) {
            //event.target is the html causing the event
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2012-11-12
      • 2013-03-23
      • 2022-08-19
      • 1970-01-01
      • 2011-04-04
      • 2011-02-10
      相关资源
      最近更新 更多