javascript - 检查数据属性是否不为空

标签 javascript jquery custom-data-attribute

我希望映射表中的所有 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 将其自己的变量分配给迭代列表:

来自documentation

callback Type: Function( Object elementOfArray, Integer indexInArray ) => Object The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.

使用前缀 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 函数混淆。

关于javascript - 检查数据属性是否不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927069/

相关文章:

javascript - 如何将变量值从 javascript 传递到 perl

javascript - 根据用户对数据库行的选择分配对象

jquery - 为 jQuery 函数设置 cookie

jquery - 使用 jQuery 为现有表添加 td

jquery 如果图像具有点击属性

javascript - 如何使用 javascript 访问 HTML 元素的数据属性

javascript - 在 AngularJS 和 JavaScript 中创建带有警报的弹出窗口

javascript - JavaScript 中的构造函数

javascript - 跨站点服务器上的 jQuery/Ajax 请求不使用该服务器上设置的 (auth) cookie

c# - 回发后如何获取HTML属性值?