检查数据属性是否不为空
Check if data attribute is not empty
我希望在 table 中映射所有 td
's/cells 并检查它们的 data
属性。如果attribute/his赋值不为空,我想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
,它将自己的变量分配给迭代列表:
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 函数混淆。
我希望在 table 中映射所有 td
's/cells 并检查它们的 data
属性。如果attribute/his赋值不为空,我想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
,它将自己的变量分配给迭代列表:
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 函数混淆。