javascript - 如何使用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>
但错误在控制台中未定义
解决方案
您没有使用特定this
绑定调用您的函数。
你可以改为传递一个参数:onclick="linkproduct(this)"
然后在你的函数中处理参数(不是this
):
function linkproduct(button){
var userId = $(button).data('rowid');
console.log(userId);
}
或者,如果您更喜欢坚持使用this
,请提供正确this
的onclick="linkproduct.call(this)"
推荐阅读
- python - 预测一个特征并使用预测的特征来预测目标
- javascript - 部署到 Firebase 会破坏使用 .click() 方法扩展引导手风琴的脚本的执行
- amazon-web-services - 使用依赖于存储桶名称的模板设置 S3 存储桶策略时如何避免循环错误?
- mongodb - pyMongo 将值设置为数组
- javascript - 如何使用 Javascript 更改 Html div 背景
- typescript - 如何使打字稿只允许来自数组的值?
- react-bootstrap - 无法使用 Preact 将自定义样式应用于 react-bootstrap 组件
- laravel - Laravel 7 Authentication 检查其他表中的用户状态
- authentication - 问:(ssg-wsg)CorpPass 不断出现错误
- java - HttpRequestBase 可以在 Dart/Flutter 中使用吗?