doushajian2018 2018-10-19 00:26
浏览 55
已采纳

如何使用javascript显示唯一的PHP数据

i have this little project i'm working on which stores data in a database using php then loads all saved data as lists into a div asynchronously. it works fine but i am currently facing a php-javascript crisis ...Here is a summary of what happens

Expected result:

  • when a list is clicked, display the unique clicked title

Actual result:

  • Always displays the title that was last saved even when a different one is clicked.

Please guys i need help to achieve the 'expected' result.

here is a snippet of the php code

//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);     
}
  • 写回答

1条回答 默认 最新

  • doucheng2053 2018-10-19 01:27
    关注

    Method 1:

    Try passing this in your onclick function,

    <span id='note-title' class='note-title' onclick='displayNote(this)'>
    

    and get your parameter on javascript also.

    <script type="text/javascript">
    function displayNote(this){
      alert(this.innerHTML)
    }</script>
    

    That should work.

    Note: It would be better if you make your id unique every loop.


    Method 2:

    Make your id unique for each loop.

    echo "<span id='note-title-".$i."' class='note-title' onclick='displayNote()'>"

    Your ids would be note-title-0 , note-title-1, ... and so on.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容