jQuery获取锚标记的数据ID

jquery get the data-id of anchor tag

本文关键字:数据 ID 获取 jQuery      更新时间:2023-09-26

我从jQuery创建了下表:

$('#btniLoad').click(function(){
var gradelevel = $('#ylvl').val();
$.ajax({
type:'POST',
url:"<?php echo site_url('enrollment/searchTeacher');?>",
dataType:'json',
data:{q:gradelevel},
success: function(data){
  if(!data.teacherinfo[0])
  {
    var table = "There's no teacher registered yet";
  }
  else
  {
    var table = "<table class='table table-striped table-bordered' cellspacing='0' width='100%'>";
    table += "<thead><th>Teacher's Name</th></thead><tbody>";
    for(var i = 0; i < data.teacherinfo.length;i++)
    {
      table += "<tr><td><a href='#teachermodal' data-toggle='modal' role='button' id='teachview' data-id='"
      +data.teacherinfo[i].teacherid+"'>"
      +data.teacherinfo[i].FirstName+', '+data.teacherinfo[i].MiddleName+', '
      +data.teacherinfo[i].LastName+"</a></td></tr>";
    }
    table += "</tbody></table>";
  }
    $('#teacherTable').empty();
    $('#teacherTable').append(table);
},
});
});

我想在控制台日志中显示 href 中的数据 id,以检查它是否正确传递了 id,但我没有从控制台日志中获得任何结果...... 这是锚标记的点击事件:

$(function(){
$('#teachview').click(function(){
var teachid = $(this).attr("data-id");
console.log(teachid);
});
});

使用 $(document).on('click','#teachview',function(){ 而不是 $('#teachview').click(function(){

ID 也应该是唯一的使用