获取任何单击的jquery的值

get the value of any clicked td jquery

本文关键字:jquery 的值 单击 任何 获取      更新时间:2023-09-26

我正在尝试获取任何点击td的值,并使用jquery或javascript在alert()窗口中显示此值。我在互联网上"搜索"了很多代码,但任何人都可以做到这一点,但无论如何我要在这里发布…

$("table tbody").click(function() {
  alert($(this).find('td.value').text());
});
$(document).ready(function() {
  $('table tbody').find('tr').click(function() {
    alert("row find");
    alert('You clicked row ' + ($(this).index() + 1));
  });
});
$(document).ready(function() {
  $('table tbody').click(function() {
    var i = $(this).index();
    alert('Has clickado sobre el elemento número: ' + i);
  });
});
$("table tbody").live('click', function() {
  if $(this).index() === 1) {
  alert('The third row was clicked'); // Yes the third as it's zero base index
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <thead>
    <tr>
      <td>id</td>
      <td>Nombre</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>miguel</td>
    </tr>
  </tbody>
</table>

为什么不直接将click事件附加到td上?您还需要确保包含jQuery…

$( "td" ).click(function() {
    alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    <table border="1">
        <thead>
            <tr>
                <td>id</td>
                <td>Nombre</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>miguel</td>
            </tr>
        </tbody>
    </table>
</body>

您需要包含jQuery库才能开始使用它。然后将点击事件绑定到td,您应该会看到alert弹出。

<head>
   <title></title>
</head>
<body>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js" type="text/javascript">
// Your code comes here

同样,下次如果有些东西不工作,你应该做的第一件事就是打开控制台,检查你是否看到任何错误并采取行动。

  • 使用console.log代替alert应该是alert完全阻塞UI线程的方式。

$("td").click(function() {
  alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
  <thead>
    <tr>
      <td>id</td>
      <td>Nombre</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>miguel</td>
    </tr>
  </tbody>
</table>