我正在处理这个小项目,该项目使用php将数据存储在数据库中,然后将所有保存的数据作为列表异步加载到div中。它工作正常,但我目前正面临php-javascript危机...这是发生情况的摘要
预期结果:
实际结果:
这是php代码的一部分
//users name
$uname = $_SESSION['username'];
//establishing connection to notes database
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
die("Connection failed:". mysqli_connect_error($dbconn));
}
//order by desc i.e Most recent appears always at the top
$result1 = mysqli_query($dbconn,"SELECT * FROM notes_log ORDER BY id DESC");
/*
loops through the query result and presents it in an array i.e
'username:title:body:date' and is displayed in the notes-log div.
*/
while($extract = mysqli_fetch_array($result1)){
if($extract['username'] === $uname){
$title = $extract['note-title'];
echo "<div class='saved-note' >";
echo "<a href='#'><span id='note-title' class='note-title' onclick='displayNote()'>". truncate($title) ."</span></a>";
echo "<div class='trig-dropdown'><span class='fa fa-ellipsis-v' id='fa-ellipsis-v'></span><div class='dropdowncontent-noteslog' id='dropdowncontent-noteslog'><a href='#'>delete</a></div></div>";
echo " <span id='note-date'> " .$extract['date-saved']."</span>";
echo "</div>";
}
}
JS
function displayNote(){
var res = document.getElementById("note-title");
alert(res.innerHTML);
}
答案 0 :(得分:0)
方法1:
尝试在您的onclick函数中传递this
,
<span id='note-title' class='note-title' onclick='displayNote(this)'>
并在javascript上获取您的参数。
<script type="text/javascript">
function displayNote(this){
alert(this.innerHTML)
}</script>
应该可以。
注意:最好让每个循环的ID都唯一。
方法2:
使您的ID在每个循环中都是唯一的。
echo "<span id='note-title-".$i."' class='note-title' onclick='displayNote()'>"
您的ID将为note-title-0
,note-title-1
等。