我正在使用一系列 来在我的网页上存储数据。
<div style="display: none;">
<span class="data_location" data-name="Joe Bloggs" data-description="Lorem ipsum" data-location="CA"></span>
<span class="data_location" data-name="Jane Doe" data-description="Ipsom erum" data-location="AN"></span>
<span class="data_location" data-name="John Doe" data-description="Dorem noloy" data-location="CZ"></span>
<span class="data_location" data-name="William Gates" data-description="Lorem ipsum" data-location="AG"></span>
<span class="data_location" data-name="Henry Kissinger" data-description="Nuymt calum" data-location="AN"></span>
</div>
我想循环遍历每个跨度,读取我的数据属性。下面的概念验证代码始终返回“未定义”。
$(document).ready(function () {
$.each(".data_location", function () {
var location = $(this).data("location")
alert(location)
});
});
我感觉问题出在 $(this) 上,但我无法识别。谁能帮帮我吗?
最佳答案
array#each
函数的解密错误。你可以这样改变 $(".data_location").each(function () {
.
为什么未定义?
您正在对每种类型应用数组方法。但是$(".data_location")
不是数组。其元素的对象
$(document).ready(function () {
$(".data_location").each(function () {
var location = $(this).data("location")
console.log(location)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display: none;">
<span class="data_location" data-name="Joe Bloggs" data-description="Lorem ipsum" data-location="CA"></span>
<span class="data_location" data-name="Jane Doe" data-description="Ipsom erum" data-location="AN"></span>
<span class="data_location" data-name="John Doe" data-description="Dorem noloy" data-location="CZ"></span>
<span class="data_location" data-name="William Gates" data-description="Lorem ipsum" data-location="AG"></span>
<span class="data_location" data-name="Henry Kissinger" data-description="Nuymt calum" data-location="AN"></span>
</div>
关于javascript - 使用 .each() 循环时获取数据属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43738078/