dsfdfd1211 2016-07-27 18:22
浏览 86
已采纳

无法在javascript中动态获取元素ID

I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.

Where am I going wrong?

foreach ($students as $student) {


echo '<tr>';
    echo '<td>
        '.$student[student_permalink].'
        <input type="submit" 
            value="info" 
            onclick="getStudentInfo()"
            class="student-name-btn" 
            id="'.$student[student_permalink].'" 

        /> 
    </td>';

}

js:

function getStudentInfo() {
    var studentLink = $('.student-name-btn').attr('id');
    console.log(studentLink);
}
  • 写回答

5条回答 默认 最新

  • duanji9311 2016-07-27 18:28
    关注

    Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.

    What most people would do is add events with jQuery and not inline.

    //needs to be loaded after the element or document ready
    $(".student-name-btn").on("click", function() {
        console.log(this.id);
    });
    

    For yours to work, you would need to pass a reference to the button that was clicked.

    onclick="getStudentInfo(this)"
    

    and than change it to use the node passed in

    function getStudentInfo(btn) {
        var studentLink = $(btn).attr('id');
        console.log(studentLink);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败