jquery获取元素名称 - prop('name')或attr('name') [英] jquery getting element name - prop('name') or attr('name')

查看:82
本文介绍了jquery获取元素名称 - prop('name')或attr('name')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过jquery获取元素名称 -

I'm trying to get element name by jquery -

请检查以下示例代码:(或 http://jsbin.com/usujeq/2/watch

please check the following example code: (or http://jsbin.com/usujeq/2/watch)

<div name = "foo1">
  <div name = "foo2">
    <div name = "foo3">
      <div name = "foo4">
        <button id = "clickme" type="button">
</div></div></div></div>

<script type="text/javascript">
$('#clickme').click( function() {
  $(this).parents().each( function() {
     console.log($(this).prop('name'));
  });
});
</script>

如果我点击 clickme ,它应该去遍及DOM从< div name =foo4> < html> 并记录下来姓名。

if I click clickme, it should go up all over the DOM from <div name="foo4"> to <html> and log their names.

预期结果是:

foo4
foo3
foo2
foo1
undefined
undefined

prop('name')返回undefined,而 attr('name')给出预期的名称。
上面代码中的 prop('name')有什么问题?

prop('name') returns undefined while attr('name') gives expected names. what is wrong with prop('name') in above code?

推荐答案

我认为这里的主要问题是 div 元素默认情况下没有 name 属性(请参阅全局属性)。如果您要在输入元素上执行原始JavaScript代码,它可能会起作用,因为 input 元素具有 name attributes。

I believe the main issue here is that div elements do not have a name attribute by default (see Global attributes). If you were to perform your original JavaScript code on input elements, it would likely work because input elements have name attributes.

jQuery的 .attr() 方法甚至可以解析非标准属性(示例)。

jQuery's .attr() method is able to parse even non-standard attributes (example).

jQuery的 .prop() 方法主要用于已检查已禁用等属性,因此使用在任何情况下, .attr()可能是最好的做法。

jQuery's .prop() method is mostly used for properties such as checked and disabled, so using .attr() is probably the best course of action in any case.

这篇关于jquery获取元素名称 - prop('name')或attr('name')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆