簡體   English   中英

在php動態創建的表中切換html屬性contenteditable

[英]Toggle html attribute contenteditable in php dynamically created table

我找到了很多文章和解決方案,但由於某種原因,我的代碼仍然無法正常工作。 我錯過了什么?

表:(創作作品,重要部分在評論'!這里')

<!-- Table with grades -->
<table class="table table-hover table-dark">
   <caption>List of grades</caption>
   <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Grade</th>
       </tr>
    </thead>
    <tbody>
    <?php
      // fill table with data of database
      if($subject != '') {
        $query = "SELECT u.firstname, u.lastname, u.username, s.subject, g.grade FROM tbl_grades as g INNER JOIN tbl_users as u on g.studentID = u.ID INNER JOIN tbl_subjects as s on g.subjectID = s.ID where s.subject = ? and classID = ? order by u.lastname";
        $stmt = $mysqli->prepare($query);
        $stmt->bind_param("ss", $subject, $class);
        $stmt->execute();
        $result=$stmt->get_result();

        if($result->num_rows > 0) {
          $count = 0;
          while($row = $result->fetch_assoc()){
            if(($count % 2) != 0) {
              echo '<tr class="bg-success">';
            } else {
              echo '<tr>';
            }
            echo '<th scope="row">' . ($count + 1) . '</th>';
            echo '<td>' . $row['firstname'] . '</td>';
            echo '<td>' . $row['lastname'] . '</td>';
            //! HERE
            echo '<td class="grade_td" contentEditable="false">' . $row['grade'] . '</td>';
            echo '</tr>';
            $count++;
          }
        }
        $result->free();
      }
    ?>
    </tbody>
</table>
<button class="btn_edit">Edit List</button>

使用 javascript、jquery 切換(多個版本,它們都不起作用):

$(document).ready(function() {
  // v1
  $('.btn_edit').click(function() {
    if($('.grade_td').contentEditable == false) {
      $('.grade_td').contentEditable = true;
    }
  });
  // v2
  $('.btn_edit').click(function() {
    $('td[contenteditable="false"]').contentEditable = true;
  });
  // v3
  $('.btn_edit').click(function() {
    $('.grade_td[contenteditable="false"]').contentEditable = true;
  });
  // more variations, same concepts
});

順便提一句。 按鈕事件工作正常

您需要使用 jQuery attr函數或在元素本身而不是 jQuery 對象上設置屬性值。

$('.btn_edit').click(function() {
  
    $('.grade_td').attr('contenteditable', 'true') ;
  
});

我不確定自定義屬性,但我會將其設為數據屬性:

echo '<td class="grade_td" data-contenteditable="false">' . $row['grade']

然后像這樣引用:

$('td.grade_td[data-contenteditable="false"]');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM