jQuery 类型错误:abc.getAttribute 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18163213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: abc.getAttribute is not a function
提问by Victor
For the following code:
对于以下代码:
<span class="map-marker" data-lng="101.7113506794"></span>
<span class="map-marker" data-lng="101.6311097146"></span>
var abc = $('.map-marker:first');
var xyz = abc.getAttribute("data-lat");
console.log(xyz);
I get the error message: TypeError: abc.getAttribute is not a function
. What have I done wrong?
我收到错误消息:TypeError: abc.getAttribute is not a function
。我做错了什么?
回答by Cherniv
Try this may be:
试试这可能是:
var abc = $(".map-marker:first")[0];
var xyz = abc.getAttribute("data-lat");
console.log(xyz);
Or this:
或这个:
var abc = $(".map-marker:first");
var xyz = abc.data("lat");
console.log(xyz);
回答by Cherniv
abc
is a jQuery object, so it doesn't have a getAttribute()
function. it has an attr()
function.
abc
是一个 jQuery 对象,所以它没有getAttribute()
函数。它有一个attr()
功能。
回答by Felix Kling
回答by user3094826
Your trying to get "data-lat" but you only have "data-lng" defined.
您试图获得“data-lat”,但您只定义了“data-lng”。
回答by Boluc Papuccuoglu
You are selecting multiple elements. The select function returns an array, and the array does not have a getAttribute function. You can use a for loop to iterate through the selection and get the attribute values, or you could use an indexer ([0], for example) to get the attribute of a particular one.
您正在选择多个元素。select函数返回一个数组,该数组没有getAttribute函数。您可以使用 for 循环遍历选择并获取属性值,或者您可以使用索引器(例如 [0])来获取特定属性的属性。
回答by chethan
Just got into this problem. Agree with @Felix Kling Try below:
刚遇到这个问题。同意@Felix Kling 尝试以下:
<span class="map-marker" data-lng="101.7113506794"></span>
<span class="map-marker" data-lng="101.6311097146"></span>
<script>
var abc = $('.map-marker:first');
var xyz = $(abc).attr("data-lng");
console.log(xyz);
</script>
回答by Riley Steele Parsons
Keep an eye out for accessing this
in an event handler with dynamic scope.
注意this
在具有动态范围的事件处理程序中的访问。
Calling a function on this
that does not exist can cause node.getAttribute is not a function
.
调用this
不存在的函数可能会导致node.getAttribute is not a function
.