使用 while 循环创建表,如果我在 body 标记内写入 html,则切换按钮可以正常工作,但如果我使用 while 循环创建表,则切换按钮不起作用。
<script src="../assets/js/jquery-1.10.2.min.js"></script>
<script src="../PurpleStyle/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
$('.jq_show_table').toggle(function () {
$(this).text('Hide');
$(".tab_taggle").show();
}, function () {
$(".tab_taggle").hide();
$(this).text('Show');
}
);
function GetLocations() {
$.ajax({
url: "Location.aspx/GetLocations",
type: "POST",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) { debugger; BindLocation(data.d); },
error: function (data) { BindLocation(data.d); },
});
}
function BindLocation(locationList) {
debugger;
var table = "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='table'>";
table += "<tr class='tab_head'>";
table += "<td width='7%'>User name</td>";
table += "<td width='4%'>Form</td>";
table += "<td width='13%'>Places Visited</td>";
table += "<td width='7%' align='center'>Setings</td>";
table += "</tr>";
table += "<tr>";
table += "<td valign='middle'>" + "User Name" + "</td>";
table += "<td valign='middle'>Form </td>";
table += "<td valign='middle'>Places Visited</td>";
table += "<td class='no-padding'>";
table += "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='tab_taggle'>";
table += "<tr><td width='54%'>GPS</td><td width='46%' class='off'>Off</td></tr>";
table += "<tr><td>Phone Network</td><td class='off'>Off</td></tr>";
table += "<tr><td>Auto Start</td><td class='on'>Off</td></tr>";
table += "<tr><td>Auto Start</td><td class='on'>Off</td></tr>";
table += "<tr><td>Connection</td><td class='on'>Off</td></tr>";
table += "</table>";
table += "<a class='btn btn_grey jq_show_table' href='#'>Show</a>"
table += "</td>";
table += "</tr>";
// }
table += "</table>";
$('#onTable').html(table);
}
<div class="tab_container">
<div id="tab1" class="tab_content">
<div class="heading">ON</div>
<div id="onTable"></div>
</div>
最佳答案
简单地说,您正在尝试将事件监听器绑定(bind)到不存在的元素。为了修复它,您应该在将该表渲染到 #onTable div 后设置事件监听器。因此,如果我是你,我会创建一个函数来绑定(bind)事件监听器,如下所示;
var initListener = function(){
$('.jq_show_table').toggle(function () {
$(this).text('Hide');
$(".tab_taggle").show();
}, function () {
$(".tab_taggle").hide();
$(this).text('Show');
});
}
然后,在 BindLocation
函数的结束标记和 $('#onTable').html(table);
行之间,我会这样调用它:initListener();
关于javascript - 通过 jquery 创建表时,Jquery 切换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33275593/