How do you make mulitple buttons call the same function when I don't know the button names?
I have a stored procedure that will return a result set with n amount of columns (the stored proc's logic determines the columns to be returned) which I use to build a "grid" on they fly. To do this I use a DataTable that I enumerate through at run time to build the DataColumns dynamically:
<table>
<thead>
<% foreach (System.Data.DataColumn column in ((System.Data.DataTable)Model).Columns)
{ %>
<th>
开发者_StackOverflow中文版 <%: column.Caption %>
<input id="Image1" type="image" src="../Content/theme/images/arrowhead-down.jpg" width="9px" height="5px"/></th>
</th>
<%}%>
</thead>
<tbody>
<%
foreach (System.Data.DataRow row in ((System.Data.DataTable)Model).Rows)
{%>
<tr>
<% foreach (var column in row.ItemArray)
{ %>
<td>
<%: column.ToString() %>
</td>
<%}%>
</tr>
<%
}
%>
</tbody>
</table>
The input of type image (button) will be included for each new column element. Essentially that button will allow for the column to be hidden using some scripting:
$(document).ready(function () {
$('#Image1').click(function () {
$('td:nth-child(3),th:nth-child(3)').hide();
});
});
So my question is this, how can I have each of the newly created buttons call the same function regardless of the name of the button (since I won't know how many buttons will be created or their names)?
Give them all the same CSS class name. Avoid hooking up JavaScript to IDs when using .NET, it likes to hog them for itself.
Then you can use:
$('.buttonClassOfYourChoice').click(function() {
....common click code...
})
"this" will refer to the button that was clicked:
$('.buttonClassOfYourChoice').click(function() {
alert($(this).html())
})
精彩评论