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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:09:09  来源:igfitidea点击:

TypeError: abc.getAttribute is not a function

javascriptjquery

提问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

abcis a jQuery object, so it doesn't have a getAttribute()function. it has an attr()function.

abc是一个 jQuery 对象,所以它没有getAttribute()函数。它有一个attr()功能。

回答by Felix Kling

What have I done wrong?

我做错了什么?

You treated a jQuery objectlike a DOM element. jQuery objects don't have a getAttributemethod. You can either use .attror .datainstead.

您处理一个jQuery对象就像一个DOM元素。jQuery 对象没有getAttribute方法。您可以使用.attr.data代替。

回答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 thisin an event handler with dynamic scope.

注意this在具有动态范围的事件处理程序中的访问。

Calling a function on thisthat does not exist can cause node.getAttribute is not a function.

调用this不存在的函数可能会导致node.getAttribute is not a function.