javascript - 单击 li 元素时无法执行功能

标签 javascript php jquery html

我有一个像这样的 HTML 列表:

<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>
例如,当我单击“2014”时,我需要隐藏其他列表并仅显示单击的列表,然后将今年传递给 php 文件,捕获今年并连接到数据库烘焙与今年相关的其他数据,然后在列表末尾列出这些新数据,我尝试了以下操作:

jQuery 部分:

<script> 
$('.year').click(function(){
var path=$(this).text();
$(".year").toggle(200);
$(this).toggle(200);
$.post("test.php",{p:path},function(data){
$(".years").append(data);
});

// last part of script
$(".col_1").click(function(){
//whatever 
});

</script>

test.php:

if(isset($_POST['p']){
$year=$_POST['p'];
$db_connection=new mysqli(localhost,USER,PASS) ;
$query="select*from user.info where year=$year" ;
$db_connection->query($query);
$rows=$db_connection->num_rows;
for($i=0;$i<$rows;$i++){`
$result->data_seek($rowP);
$result->fetch_assoc()["col_1"];
$returned_data.="<li class='col_1'>$result</li>";
}
echo "$returned_data";
}

所有这些工作都很好,数据显示在网页中,但脚本的最后部分不起作用,当我单击此列表的任何元素时,什么也没有发生。原因是因为<li class='col_1'>由 php 或什么编码?..感谢帮助。

最佳答案

只需将 $(".col_1").click(function(){ 移至 ajax 中的 Success 函数内

$('.year').click(function(){
  debugger;
  var path=$(this).text();
  $(".year").toggle(200);
  $(this).toggle(200);
  $.post("test.php",{p:path},function(data){
    $(".years").append(data);
    $(".col_1").click(function(){
    //alert();
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='years'>
<li class='year'>2014</li>
<li class='year'>2015</li>
<li class='year'>2015</li>
</ul>

关于javascript - 单击 li 元素时无法执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43183919/

相关文章:

jquery - 限制 jQuery fadeIn()

javascript - 未打开主页时使标题变小?

javascript - REST API 错误 : Refused to connect to . .. 因为它违反了以下内容安全策略指令:

javascript - 使用项目依赖项的输入定义 Gradle 任务?

javascript - OpenLayers 从 map 中删除图层

php - 使用 file_get_contents() 时出现问题

java - 如何在没有 ember-cli 的情况下通过 PHP 或 java 使用 ember js?

javascript - 在 Material UI 的 <ListItem> 中的primaryText左侧添加一个图标

javascript - 带有 node.js 的 http 请求在发送后无法设置 header

php - 如何循环并显示按日期分组的 MYSQL 查询结果?