从表格单元格获取属性到脚本

时间:2017-08-20 00:57:18

标签: javascript jquery

我正在生成一个包含如下行的HTML表:我已经能够成功获取ID和trackingNumber值,但我正在尝试获取data-categoryName-id值而我是难倒。这是我的剧本:

$("input[type='text']").change(function() {
  var parent = $(this).parents('tr');
  var recid = $(this).closest('td').attr('id');
  var trackingNumber = $(this).val();


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<tr id="53462365">
  <td>JB44566</td>
  <td>SKU123</td>
  <td>CARTON PAPER A4</td>
  <td>PAPER</td>
  <td></td>
  <td>966257111</td>
  <td></td>
  <td id="53462365"><input type="text" class="form-control" placeholder="Tracking #" name="trackingNumber" data-categoryName-id="Office Supplies" autocomplete="off" value=""></td>
  <td id="53462365"><input type="number" id="53462365" class="form-control" autocomplete="off" placeholder="ID Tag" name="idTag" value=""></td>
</tr>

尝试添加其他内容,例如:

var categoryName =

返回当前行的data-categoryName-id的值,但完全被难倒。

2 个答案:

答案 0 :(得分:0)

您可以使用.attr()

&#13;
&#13;
$("input[type='text']").change(function() {
  var parent = $(this).parents('tr');
  var recid = $(this).closest('td').attr('id');
  var trackingNumber = $(this).val();
  var categoryName = $(this).attr('data-categoryName-id');
  console.log(categoryName);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<tr id="53462365">
  <td>JB44566</td>
  <td>SKU123</td>
  <td>CARTON PAPER A4</td>
  <td>PAPER</td>
  <td></td>
  <td>966257111</td>
  <td></td>
  <td id="53462365"><input type="text" class="form-control" placeholder="Tracking #" name="trackingNumber" data-categoryName-id="Office Supplies" autocomplete="off" value=""></td>
  <td id="53462365"><input type="number" id="53462365" class="form-control" autocomplete="off" placeholder="ID Tag" name="idTag" value=""></td>
</tr>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

jQuery有一个.data()方法,允许您获取或设置data-*属性:

var categoryName = $(this).data('categoryName-id');