在表格行上单击,警告框显示单击值

时间:2016-06-12 04:09:42

标签: javascript ajax

我遇到问题,当我点击桌子时,没有显示任何内容。 enter image description here

当我点击时,让我们说出客户名=' John'的行,名称' John'应出现在警告框中,但没有任何反应。

这是我的表格点击代码。

$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});

而且,这是我生成的表格代码。

if(!empty($_GET['q'])){
$q = $_GET['q'];
$query="select * from customer where customername like '$q%'";
$result = mysqli_query($dbconn,$query);
echo "<div id='parentElementIdHere'>";
echo "<table id='test' border=3>
<tr>
<th>Customername</th>
<th>nric</th>
<th>email</th>
<th>mobileno</th>
<th>telephoneno</th>
<th>address</th>
<th>postalcode</th>
<th>datejoined</th>
<th>points</th>
</tr>";
while($row =  mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['customername'] . "</td>";
echo "<td>" . $row['nric'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['mobileno'] . "</td>";
echo "<td>" . $row['telephoneno'] . "</td>";
echo "<td>" . $row['occupation'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['postalcode'] . "</td>";
echo "<td>" . $row['datejoined'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
} 
echo "</table>"; 
echo "</div>";
}

问题可能是因为我的表因ajax而不断变化吗?

3 个答案:

答案 0 :(得分:2)

获取名称值以单击行的任何值

          $("tr").click(function() {
          var str = this.innerText;
          var i = str.split('').indexOf("   ");
          alert(str.slice(0, i));
        })

http://codepen.io/nagasai/pen/QENwgQ

点击

获取表格单元格值
 $("td").click(function(){
  alert(this.innerText);
  })

codepen网址供参考 - http://codepen.io/nagasai/pen/jrqEBz

希望这对你有所帮助

答案 1 :(得分:0)

您的代码存在两个主要问题:

  1. 您的选择器'#test tr #name'说要选择id="name"所有后代元素的元素,但它实际上是所有具有该ID的元素。 (说到它们所有具有相同的ID,重复的ID是无效的HTML。)

  2. 调用.click()将点击处理程序绑定到当时存在的元素。这意味着当您的表因Ajax调用而发生更改时,即使您修复了选择器,单击处理程序也不适用于新加载/创建的元素。

  3. 这两个问题的解决方案是使用委托的事件处理程序,它绑定到表元素的父级(或者不会被Ajax调用覆盖的最近的祖先元素):< / p>

    $(document).ready(function(){
      $("#parentElementIdHere").on("click", "#test tr", function(e) {
        var name = $(this).find("td").first().text();
        alert(name);
      });
    });
    

    当在父元素的任何后代元素上发生单击时,jQuery将检查特定单击元素是否与作为the .on() method的第二个参数的选择器匹配,如果是,它将使用{{{{}}调用您的函数1}}设置为匹配元素。因为匹配元素是tr元素,所以您可以使用this来获取该行的名称td。

    演示:https://jsfiddle.net/269Lt9hm/

答案 2 :(得分:0)

我设法解决了这个问题。我用非ajax生成的sql表测试并做到了。然后我把javascript代码带到这个文件并试了一下。这是我使用的代码。

$(document).ready(function(){
}).on('click','.test tr',function(){
var id = $(this).attr('value');
alert(id);
});

感谢所有帮助过我的人,我很感激!