creating span IDs on the fly for later use in jquery
I have some PHP code which runs a loop, spitting out a button and a span, each time it loops, like this:
(inside loop)
echo "<span id=\"sendbutton\"> <input type=\"button\" event='$eventID' id=\"sendsomeone\" value=\"Send a family member\"/> </span>";
echo "<span id=\"nameshere\"></span>";
Later in my code, I have jquery that catches one of the button clicks, and does code, then writes back. What I want it to do is to write back to the span immediately following the button that was clicked.
$('#nameshere').append('Hey! this was the button that you clicked!');
Clearly, in my example, it does not quite work the way I want. Each loop creates a span with an id of nameshere, and so when I click any of the buttons, it appends to the topmost span. I could easily use $eventID
as the span ID, but I don't know how to accurately reference it in my javascript.
How can I have it append to the button that was clicked开发者_运维问答? $(this)
perhaps? I just don't know how to use it correctly.
Edit, more info:
My click code looks like this:
$('input:button').click(function() {...}
Even more info:
I should have asked more clearly. I can make my span ID unique. I just set it to be $eventID. Done. But how do I call that from in jquery?
You can't have elements with duplicate ids. Change your Id's to classes and try this.
$("input.sendsomeone").click(
$(this).next("span").html('Hey! this was the button that you clicked!')
);
As i understand the better way is to add at yours "nameshere" any id number, and to store the same id at yours button, so you can link them to each other
Well, you can do some like this:
(inside the loop):
echo "<div>";
echo "<span id=\"sendbutton\"> <input type=\"button\" event='ClickMe(this)' id=\"sendsomeone\" value=\"Send a family member\"/> </span>";
echo "<span id=\"nameshere\"></span>";
echo "</div>";
(It can be any tag but div indeed) Then the function ClickMe:
function ClickMe(button)
{
var span = button.parentNode.parentNode.getElementsByTagName('span')[1]; // Here you got your span!!
}
精彩评论