Javascript 如何使用jquery查找所选行

Javascript 如何使用jquery查找所选行,javascript,jquery,html,Javascript,Jquery,Html,我有一个表格和一个按钮来获取所选行: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td></tr> <tr id="3"><td>Tes

我有一个表格和一个按钮来获取所选行:

<table id="mytable" class="table-striped">
    <tbody>
        <tr id="1"><td>Test1</td></tr>
        <tr id="2"><td>Test2</td></tr>
        <tr id="3"><td>Test3</td></tr>
        <tr id="4"><td>Test4</td></tr>
        <tr id="5"><td>Test5</td></tr>
    </tbody>
</table>
<button id="btn">Get Selected Row</button>
问题是当我单击按钮时,如何使用jquery获取所选行(背景色为红色)


以下是我所做的:

因为您正在将
.higlight
类添加到单击的行中,然后使用这些类查找它:

function getRow() {
  // here you need to return the value
  // to be available when function was called
  return $('table > tbody').find('.highlight');
}

$('#btn').click(function (e) {
  var selrow = getRow();
  // index of selected row
  alert('Index is :' +selrow.index());
  // text of selected row
  alert('My text is :' +selrow.text());
});

由于要将
.higlight
类添加到单击的行中,请使用这些类查找它:

function getRow() {
  // here you need to return the value
  // to be available when function was called
  return $('table > tbody').find('.highlight');
}

$('#btn').click(function (e) {
  var selrow = getRow();
  // index of selected row
  alert('Index is :' +selrow.index());
  // text of selected row
  alert('My text is :' +selrow.text());
});

您可以将具有
.highlight
类的任何行与
tr.highlight
匹配

如果需要jQuery对象(如果找到匹配项),则需要在
getRow()函数中返回它:

function getRow() {
    return $('table > tbody > tr.highlight');
}

您可以将具有
.highlight
类的任何行与
tr.highlight
匹配

如果需要jQuery对象(如果找到匹配项),则需要在
getRow()函数中返回它:

function getRow() {
    return $('table > tbody > tr.highlight');
}

你可以这样做

$(".table-striped > tbody > tr").each(function()
    if ($(this).hasClass("highlight"))
        console.log($(this).attr("id"));
);

这样,它将在lçog上打印所选行的id

您可以这样做

$(".table-striped > tbody > tr").each(function()
    if ($(this).hasClass("highlight"))
        console.log($(this).attr("id"));
);

通过这种方式,它将在lçog上打印所选行的id

您正在添加一个类
突出显示
,从那里您可以获得它您正在添加一个类突出显示,从那里您可以获得它