2017-08-08 135 views
0
<?php 
//Load the database configuration file 
include 'dbConfig.php'; 

$sql  = "SELECT * FROM users ORDER BY level DESC LIMIT 500"; 
$result = $db->query($sql); 
if ($result->num_rows > 0) { 
    $i = 0; 
    while ($row = $result->fetch_assoc()) { 

     echo '<ul class="list-group"> 
    <li class="list-group-item"> 
    <span class="badge">' . $row['level'] . '</span> 
    <img id="' . $i . '" onclick="image();" width="30px" height="30px" src="' . $row['picture'] . '"><strong>&nbsp;' . $row['first_name'] . ' 
    </strong></li> 
    <script> 
function image(this) { 
    console.log($(this).attr("id")); 
} 
    </script> 
    '; 
    $i ++; 

    } 
} 
?> 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 

这是为什么不工作? 问题:Console.log正在返回undefined。 为什么我会收到未定义的消息?有避免它的好方法吗?CONSOLE.LOG返回undefined

+1

这个问题是因为当通过'上*'事件属性调用的函数的范围是'window',而不是元素本身,因此'this'是不是你期待它。请参阅标记为解决方案的副本。另外请注意,使用'on *'事件属性是令人难以置信的过时,应该避免。请使用不显眼的事件处理程序。 –

+0

尝试围绕下面的脚本: jQuery(document).ready(function($){ )}; –

回答

0

查看下面的示例。你可以通过jQuery实现它。

$(document).ready(function(){ 
 
$("img").click(function(){ 
 
    alert($(this).attr("id")); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="img_123" width="30px" height="30px" src=""><strong>test </strong>

+0

这就是我一直在寻找的,谢谢! –

+0

欢迎你高兴帮助你:) @HossemHamami – RJParikh