2011-08-30 44 views
1

我有一些PHP代码,它会生成一些项目,它本身不是一个列表,但我们可以这样想。jquery按钮和多个项目

对于每个项目,我有PHP生成一个按钮。

我需要jquery才能够注册这些按钮中的任何一个的点击,然后根据点击的订单项执行代码和抓取值。

所以我可能有这样的代码(在我的循环语句)

<br>There is a duel being held on turn $eventturn between $name1 of house $fname1 and $name2 of house $fname2! <input type=\"button\" id=\"sendsomeone\" value=\"Send a family member to spectate\"/>" 

和jQuery这样的代码

$('#sendsomeone').click(function() { 
    alert("button was clicked."); 
}); 

正如我敢肯定,你可以猜到,这只是在为谁工作一个项目,而不是多个项目。

我如何能让jquery注册不同按钮点击,并为他们抓取数据?

回答

2

$('input:button').click(function() {...});会把相同的点击处理程序上的所有按钮一次。

点击处理程序可以抓取存储在按钮某个属性中的文本;您可以更改每个按钮的属性值,而不会影响HTML呈现。例如:

<button blah="whatsit">Click me</button> 
<button blah="ooga">Click me too</button> 

而且这个脚本:被点击第一个按钮和“OOGA”点击第二时

$('input:button').click(function() { alert($(this).attr("blah")) }); 

会弹出“的whatsit”。

1

而不是将id属性添加到您的按钮,使用class属性。 ID必须是唯一的,但类不是。 JQuery的匹配使用此语法类:$('.sendsomeone')

<input type=\"button\" class=\"sendsomeone\" value=\"Send a family member to spectate\"/> 
... 
$('.sendsomeone').click(function() { 
    alert('Button clicked'); 
}); 
+0

如果您使用$ .live()绑定您的事件,则可以在不更改的情况下添加/删除客户端。 – lucifurious

0

给你的按钮一个唯一的ID(ID = “sendsomeone1” ID = “sendsomeone2” ...)和同一类(CLASS = “sendsomeone”),并添加点击句柄类:

<input type="button class="sendsomeone" id="sendsomeone1" value="send 1" /> 
<input type="button class="sendsomeone" id="sendsomeone2" value="send 2" /> 

$('.sendsomeone').click(function() { 
    alert('Button '+$(this).attr('id')+' was clicked!"); 
}); 
0

我想你想要的东西,如:

$('#sendsomeone, #sendanother, #stillanotherone).click(....); 

你可以明显也给所有按钮同一类,做:

$('.youclass').click(...); 

请注意,在所有这些情况下,这个中的函数将成为发起事件的按钮。