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

无法在javascript中动态获取元素id,javascript,php,jquery,Javascript,Php,Jquery,我有一份学生名单,我正在循环浏览并添加到我的页面。每个学生都有一个唯一的ID,当调用getStudentInfo时,它会对ID进行处理。问题是,无论我单击哪个学生,我都会返回属于student1的相同ID 我哪里做错了 foreach ($students as $student) { echo '<tr>'; echo '<td> '.$student[student_permalink].' <input type="

我有一份学生名单,我正在循环浏览并添加到我的页面。每个学生都有一个唯一的ID,当调用
getStudentInfo
时,它会对ID进行处理。问题是,无论我单击哪个学生,我都会返回属于student1的相同ID

我哪里做错了

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>';

}

您可以在
onclick
事件中将引用传递给正在单击的元素

foreach ($students as $student) {


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

        /> 
    </td>';

}

不要使用内联事件-没有必要用它来混乱HTML。元素上有一个公共类,所以只需创建一个jQuery处理程序并使用
this

$('.student-name-btn').click(function() {
    var id = this.id;
});

就像提到的@epascarello一样,您没有选择实际单击的按钮。您应该在JS中而不是HTML中进行事件处理,以便更好地了解它的工作原理,并在闭包中使用
this
关键字来引用单击的按钮

$(document).on('click', '.student-name-btn', function(evt) {

    // Prevent default if trying to do your own logic
    evt.preventDefault();

    // Need to use the "this" keyword to reference the clicked element
    var studentId = $(this).attr('id');

    console.log(studentId);

});

您的代码正在使用该类选择页面上的所有按钮,然后读取列表中第一个按钮的id。您没有将其限制为已单击的

大多数人会使用jQuery添加事件,而不是内联

//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
    console.log(this.id);
});
要使您的应用程序正常工作,您需要传递对已单击按钮的引用

onclick="getStudentInfo(this)"
然后将其更改为使用传入的节点

function getStudentInfo(btn) {
    var studentLink = $(btn).attr('id');
    console.log(studentLink);
}

您可以在不使用内联JavaScript的情况下执行此操作,因为您正在使用jQuery,所以请删除
onClick()
和表单元素:

echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
     '.$student['student_permalink'].' 
      </td>';

因为您没有选择单击的按钮。不要使用内联事件。不是这样,我有很多行学生,我单击了对应行的每个按钮。$('.student name btn')选择页面上的所有按钮,然后在阅读attr()id时选择第一个元素。哦,我明白你的意思了。那么,我如何动态地获取ID呢?
el.ID
就足够了,真的不需要为这么简单的事情使用库
$(btn).attr('ID')
=
btn.ID
从技术上讲它是
$(btn).attr('ID')==btn.ID
;)
function getStudentInfo(btn) {
    var studentLink = $(btn).attr('id');
    console.log(studentLink);
}
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
     '.$student['student_permalink'].' 
      </td>';
$('td').click(function() {
    var studentLink = this.id;
    console.log(studentLink);
});