php - Javascript 变量 - 未定义

标签 php javascript jquery

为什么当我点击一个表格行时,它会提示该行的数据属性为“未定义”?

$(document).on('click', 'tr', function() {

    alert($(this).data("recordId"))

});

这是(成功)将 fee_source_id 变量作为数据属性传递到表行中的 PHP

<table = "all_aifs">
<tr>
    <th><b>Invoice ID</b></th>
    <th><b>Company Name</b></th>
    <th><b>Invoice Date</b></th>
    <th><b>Link</b></th>
</tr>
<?php foreach($result as $index => $row) : ?>
<tr data-recordId="<?=$row[id];?>"
    class="<?=$row["match"] ? "match" : "";?>">
    <td><?php echo $row[id]; ?></td>
    <td><?php echo $row[company_name]; ?></td>
    <td><?php echo $row[invoice_date]; ?></td>
    <td></td>
</tr>

更新 感谢下面的评论,我发现上面的 JavaScript 代码中存在一些错误,如下所示:

  1. 警报方法正在调用 data 元素而不是 attr 元素。
  2. attr 方法的参数已更改为 ("data-recordId")。 (注意:jQuery 知道忽略此参数的第一部分,因此 data- 未作为参数包含在内。)
  3. alert 方法末尾缺少一个分号

更新了 jQuery(现在有效)

$(document).on('click', 'tr', function() {

    alert($(this).attr("data-recordID"));

});

问题:

  • 我正在使用支持 $.on() 的 jQuery 1.7.2 并且还应该支持 .data() 等等,我原来的 positng 应该使用.data() 方法仍然有效?为什么它不起作用?
  • 不是将数据属性设置为“x”,因为它正好等于表中每一行的第一列,(fee_source_id) 我可以只使用第一列/表格每一行的单元格而不是已传递的数据属性,以引用该记录?

最佳答案

I am using jQuery 1.7.2 which supports the $.on() and should also support the .data() and so, should my original positng which uses the .data() method still work? Why is it not working?

如果您使用.data 访问数据属性,you're actually reading from jQuery's data object ,这恰好将 cameCased 键映射到带连字符的键 (recordId -> record-id)。这意味着如果您将属性重命名为 data-record-id,您可以使用 .data('record-id').data(' recordId')See a demontration .

Instead of setting the data-attribute to be "x", since it is exactly equal to the first column of each row in the table, (fee_source_id) could I just use the first column/cell in each row of the table instead of the data-attribute which has been passed, to make reference to that record?

是的,你可以这样做(示例包含在同一个 demo 中):

$(document).on('click', 'tr', function() {
    var record_id = $(this).find('td:first-child').text();
    alert(record_id);
});

关于php - Javascript 变量 - 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14179422/

相关文章:

javascript - 使用 Jquery 隐藏和显示动态创建的 UL 列表?

php - 如何使我的三表 sql 连接工作?

php - 如何在 PHP 中通过 CheckBox 填充数据库单元格是或否?

javascript - 如何解决跨域请求被阻塞?

javascript - isCustomResponse() API - 是否可用 MFPF8

javascript - 为什么单击一个按钮会影响 jQuery Ajax 中的所有按钮

javascript - 使用 MVC5 C# 和 Razor 在部分 View 中运行 javascript

php - jQuery 'on' 事件,检查是否为 NOT ON

php - Wordpress 时间线每季度添加标题 1 月至 3 月等等

javascript - 如何获取选中复选框的所有名称?