【问题标题】:What's the best way of attaching an on-click event to a table cell?将点击事件附加到表格单元格的最佳方式是什么?
【发布时间】:2019-06-02 14:09:31
【问题描述】:

我正在尝试将单击事件附加到表格单元格,因此当单击它时,它的背景会改变颜色,并且显示“是”的文本会出现在中间。我还希望它在控制器类中触发 PHP 方法。

我有如下代码:

// index.html

```

<table>
    <thead>
   <tr>
   <th>Heading</th>
   </tr>
   <thead>
   <tbody>
   <tr class="clickme">
   <td><a onclick="reserve();return false;" href={{route('submitaction', 
   $colour->colour_id) }}</a></td> // On click, change its background 
   colour.
   <td></td>
    </tr>
</tbody>

//scripts.js

function reserve(){

 $(this).addClass('newColour');

}

//flow.live.css

   .newColour {
    background-color: gray;
    content: 'Yes';
    text-align: center;
    }

我将填充链接以填充整个表格单元格,并在用户单击链接时触发事件。我正在尝试做的事情是否明智,还有其他聪明的解决方法吗?

谢谢, 抢

【问题讨论】:

    标签: php html css laravel-5


    【解决方案1】:

    我使用了不同的标记,因为您没有提供 CSS。

    您需要将事件委托给父元素。

    我在其他网站上使用过这个标记:

    <table id="customers">
    <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
    </tr>
    <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
    </tr>
    <tr>
    <td>Berglunds snabbköp</td>
    <td>Christina Berglund</td>
    <td>Sweden</td>
    </tr>
    <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
    </tr>
    <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
    </tr>
    <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
    </tr>
    <tr>
    <td>Königlich Essen</td>
    <td>Philip Cramer</td>
    <td>Germany</td>
    </tr>
    <tr>
     <td>Laughing Bacchus Winecellars</td>
     <td>Yoshi Tannamuri</td>
     <td>Canada</td>
     </tr>
     <tr>
     <td>Magazzini Alimentari Riuniti</td>
     <td>Giovanni Rovelli</td>
     <td>Italy</td>
      </tr>
     <tr>
     <td>North/South</td>
      <td>UK</td>
     </tr>
     <tr>
     <td>Paris spécialités</td>
    <td>Marie Bertrand</td>
    <td>France</td>
    </tr>
    </table>
    

    这里是 JS:

    $( "#customers" ).on( "click", "td", function( event ) { // target the outermost parent element, this will delegate the event to the element specified as second arg on the callback function
    $(this).addClass('newColour'); // Here you just add the class, no inline JS needed.
    
     });
    

    就是这样,阅读事件委托以及它为什么有用并在这里尝试工作代码,没有 PHP 代码,但你最大的问题是 JS。:

    https://codepen.io/damPop/pen/JwZXya

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      相关资源
      最近更新 更多