如何在单击表格内的按钮时打开模态对话框?
function GetAllCountries() {
$('#update_panel').html('Loading Date....');
$('#update_panel').html("<img src='/Pic/ajax-loader.gif'/>")
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table id="tableItems"> </table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
});
$('#update_panel').html($data);
}
else {
var $noData = $('<div/>').html('No Data Found!');
$('#update_panel').html($noData);
}
},
error: function () {
alert('Error! Please try again.');
}
});
}
我尝试了以下代码,但没有工作
$("#mybtn").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,
});
$("#CreateForm").dialog('open');
})
我想我需要点击表格中的按钮并添加点击事件
$("#Table: Tbody,th,tr").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,
答案 0 :(得分:2)
创建按钮时,您还必须设置click event
。在元素初始化之前创建的任何事件都不会附加到该特定元素。所以改变你的代码:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
对此:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$button = $('<button />', {class: 'whatever', id: 'myButton' /* AND SO ON */};
$($button).click(function() {
// CODE TO OPEN THE MODAL
});
$row.append($button);
$data.append($row);
*编辑*
beanId recover
我希望代码清楚。无论如何使用HTML5数据属性,您可以轻松恢复您必须编辑的bean的ID。您还可以使用动作锚点打开模态,并设置为模态特定值。
$(document).ready(function() {
$('.actionButton').click(function() {
// Recover data-bean-id tag value
var beanId = $(this).data('beanId');
// Do whatever you want
alert('Bean value:' + beanId)
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- ** The 'actionButton' anchor can be also used to open a modal -->
<table id="myTable">
<thead>
<tr>
<td>#</td>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>ACTIONS</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="1">ACTION</a></td>
</tr>
<tr>
<td>2</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="2">ACTION</a></td>
</tr>
<tr>
<td>3</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="3">ACTION</a></td>
</tr>
</tbody>
</table>
&#13;