Jquery / Ajax used on PHP page in a for loop
I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<开发者_Python百科input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
- http://api.jquery.com/attribute-starts-with-selector/
- http://api.jquery.com/delegate/
精彩评论