检查数据属性是否不为空



我希望映射表格中的所有td/单元格并检查它们的data属性。如果属性/他分配的值不为空,我想console.log它。

我现在得到了这个,但它似乎无法正常工作(它只是说所有td都不空)。另外,我不确定为什么map函数中的this指向window对象而不是确切的td。任何想法我错过了什么?

function checkTds() {
    var $tab = $('table td');
    $.map($tab, function(){
        console.log($(this));
        if ($tab.attr("custom-data-attribute") !== "") {
            console.log($(this));
        }
    });
}
checkTds();

您正在使用map,它将自己的变量分配给迭代列表:

文档

回调 类型: 函数( 对象元素数组, 整数索引数组 ) => 对象 用于处理每个项的函数。函数的第一个参数是数组项,第二个参数是数组中的索引 函数可以返回任何值。返回的数组将被平展为生成的数组。在函数中,这是指全局(窗口)对象。

使用前缀data来创建自定义属性也是标准的:data-«yourname» .

function checkTds() {
  var $tab = $('table td');
  $.map($tab, function(element) {
    //look at the element var here
    //also check if the attribute exists!
    if ($(element).attr("custom-data-attribute") && $(element).attr("custom-data-attribute") !== "") {
      console.log($(element).attr("custom-data-attribute"));
    }
  });
}
checkTds();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td custom-data-attribute="1"></td>
    <td></td>
    <td></td>
    <td custom-data-attribute="4"></td>
  </tr>
</table>


附带说明:我个人建议在使用jQuery时不要使用带有前缀$的变量。这使得将它们与实际的jQuery函数混淆变得更加容易。

最新更新