想问下,使用了 jquery 的 .html() 在网页上添加的 html 内容,在网页源代码中是没办法查看到的吗?

2020-02-21 15:05:54 +08:00
 dongchen

之所以这么问是因为,使用 jquery 在网页上显示了一个列表,现在想实现列表行批量删除的功能,选择 select_all 后所有复选框都会被选上,如果其中一个框被取消选择,那么 select_all 则取消被选上。 js 代码

$("#select_all").change(function(){
    $(".checkbox").prop('checked', $(this).prop("checked"));        
});

$('.checkbox').click(function(){     
    if($(this).prop("checked") == false){
        $('#select_all').prop('checked', false);
     }
});

列表头部是写在 html 里的

<table class="table">
  <thead>
    <tr>      
      <th scope="col"><input type="checkbox" id="select_all" /></th>
      <th scope="col">用户名</th>
      <th scope="col">登录时间</th>
      <th scope="col">全名</th>
      <th scope="col">操作</th>
    </tr>
  </thead>
  <tbody id='adminlist_tbody'></tbody>
</table>

列表的 tbody 是用 jquery 加载的

$('#adminlist_tbody').html(data.adminlist_tbody);
$('#pagination_link').html(data.pagination_link);

后端用的是 php 的 ci 框架

$tbody = '';
foreach($results as $result)
{
	$tbody .= '
	<tr>      
		<td><input type="checkbox" class="checkbox" data-id="'.$result['id'].'" /></td>
		<td>'.$result['username'].'</td>
		<td>'.$result['logintime'].'</td>
		<td>'.$result['fullname'].'</td>
		<td>
			<a class="btn btn-primary" href="#">编辑</a>
			<a class="btn text-white bg-danger" href="#">删除</a>
		</td>
	</tr>
	';
}


$data = array(
	'pagination_link'  => $this->pagination->create_links(),
	'adminlist_tbody'   => $tbody
);


exit (json_encode($data));

列表成功后发现,tbody 中的内容不会显示在 html 源码中,导致

$('.checkbox').click(function(){     
    if($(this).prop("checked") == false){
        $('#select_all').prop('checked', false);
     }
});

无法运行生效。 请问这个问题有什么好的解决方法吗?

PS. php,js 新手😂

893 次点击
所在节点    问与答
5 条回复
ysc3839
2020-02-21 18:54:37 +08:00
不要在网页加载时设置事件,动态加载网页代码之后再设置事件。
ysc3839
2020-02-21 18:56:08 +08:00
或者后端改成直接返回原始数据,前端 js 进行网页渲染,这样在渲染的时候可以直接设置事件。
ji39
2020-02-21 22:09:32 +08:00
jquery
ji39
2020-02-21 22:11:06 +08:00
使用 jquery on()
dongchen
2020-02-22 10:09:17 +08:00
@ji39
@ysc3839


```
$(document).on('click','.checkbox',function(){
if($(this).prop("checked") == false){
$('#select_all').prop('checked', false);
}
});
```
使用上面的代码就不会失效了,单独使用 jquery on() 还是不行,需要 $(document).on 才可以 ,想问下这两者有什么区别

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/646369

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX