我希望在一个表中映射所有td的/单元格,并检查它们的data属性。如果属性/他的赋值不是空的,我想要对其进行console.log。
我现在知道了,但它似乎不能正常工作(它只是说所有的td都不是空的)。而且,我不知道为什么映射函数中的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();发布于 2017-10-25 08:05:04
您使用的是map,它将自己的变量赋值给迭代列表:
来自http://api.jquery.com/jquery.map/
回调类型:函数( Object elementOfArray,Integer indexInArray ) =>对象--用于处理每个项的函数。函数的第一个参数是数组项,第二个参数是数组中的索引,函数可以返回任何值。返回的数组将被扁平化为结果数组。在函数中,它引用全局(窗口)对象。
使用前缀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函数混淆起来更加容易。
https://stackoverflow.com/questions/46927069
复制相似问题