down00112 2018-12-03 12:55
浏览 27

如何将PHP回显按钮的文本拖入Javascript,其值将用于另一个PHP Sql查询?

I have a PHP sql query that returns a table.

while($row = $result->fetch_assoc()) {
                echo "<tr><td id=\"cst\"><button type=\"submit\" id=\"click\" onClick=sendData(this)>".$row["Name"]</button></td></tr>";

The table is output correctly. My next step is using vanilla Javascript to pull the HTML text value associated with $row["Name"] from the button in the output table (when the button is clicked). I call the function onClick=sendData(this)

Now, in Javascript I'm attempting to access the text value like so:

function sendData(name) {
    var text = name.innerText;
}

However, this isn't working. Can anyone explain why?

  • 写回答

2条回答 默认 最新

  • drxrgundk062317205 2018-12-03 13:44
    关注

    The yet another variant is to improve formatting of your HTML output by taking advantage of HEREDOC syntax that suits well for complex formatting

    while($row = $result->fetch_assoc()) {
        echo <<<HTML
          <tr>
              <td class="cst"> <!-- class instead `id` -->
                  <button
                      type="button" <!-- `button` type instead of `submit` -->
                      class="btn-click" <!-- class instead `id` -->
                      data-name="{$row["Name"]}">
                         {$row["Name"]}
                  </button>
              </td>
          </tr>
    HTML;
    

    And using vanilla JS it is possible to make smth. similar to the result snippet below.

    document.addEventListener('click', function(event) {
      var target = event.target;
    
      // If the clicked element doesn't have the right selector, bail
      if (!target.matches('.btn-click')) {
        return;
      }
    
      var name = target.getAttribute('data-name');
      
      alert('Button `data-name` is "' + name + '"');
    
      // sendData logic goes further ...
    }, false);
    <tr>
      <td class="cst">
        <button type="submit" class="btn-click" data-name="Coockaracha">Reveal my name</button>
      </td>
    </tr>

    The approach of using global click listener is called event delegation and has some advantages. You can read about it here.

    Also keep in mind that id should be unique across the page, so it is not correct to iterate using id. class attribute suits nicely and allows multiples.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b