gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:48:13 25 4
gpt4 key购买 nike

我希望映射表中的所有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com