简体   繁体   中英

Help me understand whats wrong with my javascript

If I do this-

alert(anchor);

I get this-

"[object HTMLLIElement]"

... ok, yep, it is the element I want. So I want to get that elements ID.

So I test it like this:

alert(anchor.attr("id"));

... but I don't get any alert, nothing. I must not be selecting an element. What am I doing wrong, what don't I understand?

There are two problems:

  • .attr() is a function jQuery objects have, you have a DOM element (you would need $(anchor) to use jQuery methods against the element).
  • You don't need it anyway, the .id property will work (and be much faster), like this:

 alert(anchor.id);

That's because attr is not a defined method or property on anchor . anchor is a raw HTML element object. It's not a jQuery object (I'm assuming you're using jQuery because you used the attr method).

To get the id, all you have to do is anchor.id . If you really want to use attr , you can do jQuery(anchor).attr("id") .

如果你使用jquery,那么你需要这个:

alert($(anchor).attr("id"));

The attr() function is part of jQuery, but you're trying to get it from a plain DOM object. You either want to use $(anchor) (to wrap the element in jQuery) or call anchor.getAttribute("id") instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM