博客
关于我
Js获取设置属性值以及jquery中的attr与prop区别
阅读量:319 次
发布时间:2019-03-04

本文共 1512 字,大约阅读时间需要 5 分钟。

HTML 行间属性与属性获取方法

在 HTML 开发中,行间属性 (inline styles) 和属性获取方法是开发者常用的功能。以下将详细介绍 setAttributegetAttribute 的使用方法,以及它们与 attr()prop() 的区别。


行间属性与 DOM 属性

在 HTML 中,行间属性可以直接写在标签内部,使用 style 属性来设置内联样式。例如:

Content

设置行间属性会在 DOM 元素的 attributes 属性中新增一个 Attr 对象。这个对象包含有属性名及其对应的值。通过 setAttribute 方法可以轻松地设置或修改行间属性。


getAttribute 方法

getAttribute 方法用于获取元素的行间属性值。它的使用方法如下:

元素.getAttribute('属性名')
  • 返回值:如果找到对应的属性,返回该属性的值;如果没有找到该属性,返回 null
  • 注意点getAttribute 仅能获取行间属性,不能获取 CSS 样式中的属性值。

示例

var div1 = document.getElementById('div1');div1.getAttribute('title'); // 返回 "divTitle"div1.getAttribute('title1'); // 返回 "divTitle1"

setAttribute 方法

setAttribute 方法用于设置或修改元素的行间属性。它的使用方法如下:

元素.setAttribute('属性名', 属性值)
  • 覆盖原有属性:如果元素已经有该属性,setAttribute 会覆盖原有的值。
  • 新增属性:可以通过该方法为元素新增自定义的行间属性。

示例

div1.setAttribute('data-source', '网站名称');

attr()prop() 的区别

在 jQuery 中,attr()prop() 方法看似相似,但它们的使用场景和内部实现有所不同。

1. 属性类型

  • attr():返回的是 HTML 标签上的属性值,属性值只能是字符串类型。
  • prop():返回的是 DOM 元素的属性值,可以是字符串、数字或布尔值。

2. 数据来源

  • attr():获取的是标签上的属性值,不能获取 DOM 元素的自定义属性。
  • prop():获取的是 DOM 元素的属性值,包括默认属性和通过 setAttribute 设置的属性。

3. 典型用途

  • attr():适用于获取标签上的属性值,例如 idclass 等。
  • prop():适用于获取 DOM 元素的属性值,例如 checkeddisabled 等布尔属性。

典型应用示例

1. 复选框的状态获取

var cb1 = document.getElementById('cb1');console.log(cb1.getAttribute('checked')); // 返回 "checked"

通过 getAttribute('checked') 可以获取复选框的状态,但需要注意的是:勾选或取消勾选复选框会修改 checked 属性,而默认的 defaultChecked 属性会在页面刷新后恢复。


总结

在开发过程中,合理使用 getAttributesetAttribute 方法可以方便地操作行间属性。对于布尔属性(如 checkedselecteddisabled 等),建议使用 prop() 方法来获取或设置其状态。

转载地址:http://hvaq.baihongyu.com/

你可能感兴趣的文章
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>