I have some PHP code which generates a number of items, its not a list per se, but we ca开发者_JAVA技巧n 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?
$('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:
<button blah="whatsit">Click me</button>
<button blah="ooga">Click me too</button>
And this script:
$('input:button').click(function() { alert( $(this).attr("blah") ) });
Will pop up "whatsit" when the first button is clicked and "ooga" when the second is clicked.
Instead of adding an id
attribute to your button, use a class
attribute. IDs must be unique but classes are not. JQuery matches classes using this syntax: $('.sendsomeone')
<input type=\"button\" class=\"sendsomeone\" value=\"Send a family member to spectate\"/>
...
$('.sendsomeone').click(function() {
alert('Button clicked');
});
Give your buttons a unique id (id="sendsomeone1", id="sendsomeone2" ...) and the same class (class="sendsomeone") and add a click handle for the class:
<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!");
});
I suppose you want something like:
$('#sendsomeone, #sendanother, #stillanotherone).click(....);
You could obviously also give all buttons the same class and do:
$('.youclass').click(...);
Note that in all these cases this in the function will be the button that originated the event.
精彩评论