如何确定哪个按钮已被点击jquery
问题描述:
我正在使用一个PHP循环来生成多个按钮元素。我怎样才能确定哪个按钮已被点击通过使用jQuery?如何确定哪个按钮已被点击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。 (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")
。
答
<?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结合优选
答
好,如果你的代码看起来像下面
$('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
});
+0
+1为了很好的解释,这里是[测试案例](http://jsfiddle.net/PAG3y/)任何人谁想要。 :) – 2011-05-04 12:29:22
答
$(function() {
$("input[type='button']").click(function(event) {
//event.target is the html causing the event
});
});
你实际上并没有把ID属性到输入。 – tomasmcguinness 2011-05-04 12:22:05
对不起,我忘了, – 2011-05-04 12:23:40
我认为,下面的任何答案现在应该解决您的问题。 – tomasmcguinness 2011-05-04 12:27:36