我有一个名为 $myList
的 li
元素数组,我试图将列表中的最新项目与另一个值(称为 $partType
) 来查看它们是否相同。具体来说,我将每个列表项中名为 data-parttype
的属性与 $partType
进行比较。
这是我的代码:
var $lastItem = $myList.last(); // getting the most recent list item
var lastPartType = $lastItem.data('parttype'); // getting the data attribute
if (lastPartType != null) { //skip all this if the list is empty
if (lastPartType == $partType) { // see if the part types are the same
alert("Last part type: " + lastPartType + ", this part type: " + $partType + ". SAME!");
} else {
alert("Last part type: " + lastPartType + ", this part type: " + $partType + ". DIFFERENT!");
}
}
在实际代码中,如果当前部件类型 ($partType
) 与文件中最新的部件类型不匹配,我的代码会向用户发送警告消息,而不是发出警报。列表(lastPartType
)。如果匹配,则会将其添加到列表中并重复该过程。最终,我的目标是确保整个列表只能有一种部件类型,当用户尝试添加与已添加的内容不同的内容时发出警告。
以下是 $myList
中的列表项之一的示例:
<li data-parttype="new" data-id="151">1099628-15-53-27<i class="fa fa-check fa-fw text-success"></i></li>
问题是,当我在整个代码中添加警报以查看发生了什么时,结果 lastPartType
始终是“未定义”。我希望如果列表为空,但即使列表充满项目,它仍然是“未定义”。
最佳答案
根据评论中的讨论,显然 $myList 是列表而不是列表项。要获取最后一项,请执行以下操作:
var $lastItem = $myList.find('li').last(); // getting the most recent list item
关于javascript - Jquery中的.data()总是返回 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402967/