我点击一个带有“return”类的按钮,我想要获得卡的id。这是一个简单的代码。
$('.return').on('click', () => {
let a = $('.return').siblings();
console.log(a);
})
for (let card of cards) {
table += `
${card._id}
${card._visitor}
${card._bookName}
${card._borrowDate}
${card._returnDate==='not fetched'?'' + '
':card._returnDate}
发布于 2021-02-26 17:11:54
你可以这样做:
let a = $(this).parent().prevAll("th").text();
$(this)
<-指单击的按钮。
.parent()
<-访问td
.prevAll("th")
<-查找th
这是摆在你面前的td
.text()
<-获取文本${card._id}
问题是你的button
不是你的兄弟姐妹th
演示
$('.return').on('click', function() {
let a = $(this).parent().prevAll("th").text();
console.log(a);
})
${card._id}
${card._visitor}
${card._bookName}
${card._borrowDate}
${card._returnDate==='not fetched'?'' + '
':card._returnDate}
发布于 2021-02-26 17:34:37
一种选择是将id
按下按钮
then you can access that id without needing to traverse.
Note you're also using ()=> in the click event, so you won't be able to use this to reference the button. Change to function() to get this, giving:
$('.return').on('click', function() {
let id = $(this).data("id");
console.log(id);
})
1
return
2
return
752
return
发布于 2021-02-26 17:36:52
您可以绕过jquery,在添加卡时使用脚本将onclick方法附加到按钮并检索卡id。
const cards = [{
_id: 1,
_returnDate: "not fetched"
},
{
_id: 2,
_returnDate: "not fetched"
}
]
const table = document.querySelector("table")
for (let card of cards) {
table.innerHTML += `
${card._id}
Click Me
`
}
function buttonClick(cardId) {
console.log("card id:", cardId)
}
https://stackoverflow.com/questions/66382951
复制相似问题