jquery 按钮和多个项目
我有一些 PHP 代码,它生成许多项目,它本身不是列表,但我们可以这样认为。
对于每个项目,我让 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 注册不同按钮点击,并为它们抓取数据?
I have some PHP code which generates a number of items, its not a list per se, but we can think of it as such.
For each item, I have PHP generate a button.
I need jquery to be able to register the clicking of any one of those buttons, and then to do code and grab values based on the line item that was clicked.
So I might have code like this (in my loop statement)
<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\"/>"
and jquery code like this
$('#sendsomeone').click(function() {
alert("button was clicked.");
});
As I'm sure you can guess, this only really works for one item, not multiple items.
How I can have jquery register different button clicks, and grab data for them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$('input:button').click(function() {...});
将同时在所有按钮上放置相同的点击处理程序。然后,单击处理程序可以抓取存储在按钮的某些属性中的文本;您可以更改每个按钮的此属性值,而不会影响 HTML 渲染。例如:
这个脚本:
单击第一个按钮时将弹出“whatsit”,单击第二个按钮时将弹出“ooga”。
$('input:button').click(function() {...});
will put the same click handler on all the buttons at once.The click handler can then grab text stored in some attribute of the button; you can change this attribute's value for each button without affecting the HTML render. For instance:
And this script:
Will pop up "whatsit" when the first button is clicked and "ooga" when the second is clicked.
不要向按钮添加
id
属性,而是使用class
属性。 ID 必须是唯一的,但类不是。 JQuery 使用以下语法匹配类:$('.sendsomeone')
Instead of adding an
id
attribute to your button, use aclass
attribute. IDs must be unique but classes are not. JQuery matches classes using this syntax:$('.sendsomeone')
为您的按钮提供唯一的 id (id="sendsomeone1"、id="sendsomeone2" ...) 和相同的类 (class="sendsomeone") 并为该类添加点击句柄:
Give your buttons a unique id (id="sendsomeone1", id="sendsomeone2" ...) and the same class (class="sendsomeone") and add a click handle for the class:
我想您想要类似的东西:
您显然也可以为所有按钮提供相同的类并执行以下操作:
请注意,在所有这些情况下,函数中的 this 将是发起事件的按钮。
I suppose you want something like:
You could obviously also give all buttons the same class and do:
Note that in all these cases this in the function will be the button that originated the event.