Jquery button onclick属性不工作


$.get($querystudent, function(response)
{
tbodystudent.empty();
console.log("Table TBODY Cleared!");
var students = response.result;
var $i = 0
$.each(students, function(_,student)
{
$i = student.ID
tbodystudent.append(
$("<tr>").append(
$("<td>").text(student.FirstName),
$("<td>").text(student.MiddleName),
$("<td>").text(student.LastName),
$("<td>").text(student.CourseID),
$("<td>").text(student.YearLevel),
$("<input></input>").attr({'type':'button','class':'button is-primary is-small','id':$i, 'onclick': select($i)}).val("Select")          
),
);
});
}, "json");

这是我当前的Jquery代码,将数据附加到带有onclick属性的主体,试图调用函数select(),

function select(x)
{
console.log('Im Here! ', x)
}

在不单击任何按钮的情况下,控制台显示已经从页面Onload开始单击了三个按钮。Console指示该函数已经被调用,并且没有单击任何按钮

Inspect还指出onclick属性没有添加到按钮属性

根据你的想法,我已经更新并让它工作。您可以查看下面的演示:

'onclick': select($i)->'onclick': 'select(' + $i + ')'

$("<input></input>")->$("<button>"):我仍在寻找$("<input>")不工作的原因

const students = [{
ID: 1,
FirstName: 'A',
MiddleName: 'B',
LastName: 'C',
CourseID: 1,
YearLevel: 1
},
{
ID: 2,
FirstName: 'A',
MiddleName: 'B',
LastName: 'C',
CourseID: 1,
YearLevel: 1
}, {
ID: 3,
FirstName: 'A',
MiddleName: 'B',
LastName: 'C',
CourseID: 1,
YearLevel: 1
}
]
function select(x) {
console.log('Im Here! ', x)
}
$.each(students, function(_, student) {
$i = student.ID
$('#tbodystudent').append(
$("<tr>").append(
$("<td>").text(student.FirstName),
$("<td>").text(student.MiddleName),
$("<td>").text(student.LastName),
$("<td>").text(student.CourseID),
$("<td>").text(student.YearLevel),
$("<button>").attr({
'type': 'button',
'class': 'button is-primary is-small',
'id': $i,
'onclick': 'select(' + $i + ')'
}).text("Select")
),
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">FirstName</th>
<th scope="col">MiddleName</th>
<th scope="col">LastName</th>
<th scope="col">CourseID</th>
<th scope="col">YearLevel</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbodystudent">
</tbody>
</table>

最新更新