Javascript 如何获取单击的表行的值?
我的问题是:如何获得单击的行和列的值 我的代码是: JS: 遗憾的是,无论我在哪里单击,这只会给我第一行的id 感谢您的帮助Javascript 如何获取单击的表行的值?,javascript,jquery,html,html-table,Javascript,Jquery,Html,Html Table,我的问题是:如何获得单击的行和列的值 我的代码是: JS: 遗憾的是,无论我在哪里单击,这只会给我第一行的id 感谢您的帮助 Ramon单击行的HTML内容 $('#posts tr').click(function(){ $(this).html(); }); 来自单击的td的文本 $('#posts tr td').click(function(){ $(this).text(); }); 如果您使用的是ajax,并且正在重画元素,则无法通过单击功能
Ramon单击行的HTML内容
$('#posts tr').click(function(){
$(this).html();
});
来自单击的td的文本
$('#posts tr td').click(function(){
$(this).text();
});
如果您使用的是ajax,并且正在重画元素,则无法通过单击功能捕获它们。您将需要附加功能:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
下面的方法应该能够找到ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
您可以尝试为您的表使用AddEventListener,它肯定会起作用。 像这样:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
同样-对于网格中的元素,不使用相同的id(比如您拥有的id=“id”)也可以,应该是不同的 去阅读一下如何在jQuery中使用
$(this)
。如果这是你的意思,我尝试了$(this),但结果是一样的谢谢,它成功了!当我看起来不工作时,我会接受这个答案,但是谢谢你的建议!在本例中,当我对元素使用相同的ID时,这有什么关系?使用选择器,我将获得唯一的ID,对吗?是的,Ramon,对于你的问题来说,这并不重要-这只是一个通知。但根据问题-使用事件监听器可以让您“监听”所需的DOM事件,不管它来自何处-ajax还是初始DOM加载好的,那么我理解:)希望它对您有用。
$(document).on('click','#posts tr td','function(){
$(this).text();
});
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});