首页 > 解决方案 > 如何使用javascript在foreach循环中获取TD的值?

问题描述

我在表中使用了一个 foreach 循环,我想在每一行上都有一个按钮,点击时我想得到那个值,所以我尝试了这段代码

@foreach($products as $product)
<tr>
   <td>
 <button onclick='linkproduct();' data-rowid="{{ $product->id }}" class="btn btn-sm btn-info">Use Current Location</button>
     </td>
       </tr>
@endforeach

javascript

<script>
    function linkproduct(){
    var userId = $(this).data('rowid');
    console.log(userId);
}
</script>

但错误在控制台中未定义

标签: javascript

解决方案


您没有使用特定this绑定调用您的函数。

你可以改为传递一个参数:onclick="linkproduct(this)"然后在你的函数中处理参数(不是this):

function linkproduct(button){
    var userId = $(button).data('rowid');
    console.log(userId);
}

或者,如果您更喜欢坚持使用this,请提供正确thisonclick="linkproduct.call(this)"


推荐阅读