Can I change the backgroundColor property value using the prop method? I'm new to programming. :)

我可以使用prop方法更改backgroundColor属性值吗?我是编程新手。 :)

This is what I have,

这就是我所拥有的,

$('ul').prop('backgroundColor','red');

I read the chapters on this book I'm reading and it is my understanding that I can change properties from the DOM using the prop method in jquery. I can change other DOM properties such as className. Why not backgroundColor? Writing this I also tried atr.

我阅读了我正在阅读的这本书的章节,我的理解是我可以使用jquery中的prop方法从DOM中更改属性。我可以更改其他DOM属性,例如className。为什么不用backgroundColor?写这个我也试过atr。

$('ul').attr('background-color','red');

In this case, attr does have access to CSS properties, correct? However when using the prop method, we do have access to some CSS properties? Why is backgroundColor created?

在这种情况下,attr确实可以访问CSS属性,对吗?但是,在使用prop方法时,我们可以访问一些CSS属性吗?为什么创建backgroundColor?

I know the best way to go about changing the background color would be to use the css method, in jquery that is. I just wanted to know if or not the prop or atr method can change the background color, and why not, if not. I believe this will give me a better understanding of the DOM.

我知道改变背景颜色的最佳方法是在jquery中使用css方法。我只是想知道prop或atr方法是否可以改变背景颜色,为什么不改变背景颜色,如果没有。我相信这会让我更好地了解DOM。

Thanks!

谢谢!

4 个解决方案

#1


1

The backgroundColor is nested property of style property of the element so .prop('backgroundColor','red'); won't works here.

backgroundColor是元素的style属性的嵌套属性,所以.prop('backgroundColor','red');不会在这里工作。

Instead, you can set property by getting DOM element. In case there is multiple element then you need to iterate over them.

相反,您可以通过获取DOM元素来设置属性。如果有多个元素,那么您需要迭代它们。

$('div')[0].style.backgroundColor = 'red';

// if there is multiple elements

$('div').each(function() {
  this.style.backgroundColor = 'red';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>a</div>

更多相关文章

  1. 使用表单字段值定制CSS属性。
  2. js获取html下拉框中选中值的自定义属性值
  3. 关于INPUT的autocomplete="off" 属性(浏览器表单默认的记忆功能)
  4. 关于 客户端发现响应内容类型为“text/html; charset=utf-8”,但
  5. HTML5新增标签与属性
  6. HTML5 Canvas 绘图方法整理 【十五、Canvas页面交互: 鼠标事件 】
  7. 不会出现Javascript context.closePath()方法
  8. CSS定位属性之间的相互作用
  9. Delphi下发送Email的方法

随机推荐

  1. PHP 实现简易的汉字验证码的思路
  2. PHP+Redis发布订阅
  3. php检查数组下标是否存在
  4. php 与 nginx 的两种处理方式
  5. PHP运算符知识点整理
  6. php检测字符串是否包含字符串
  7. PHP 实现常用数据结构之链表
  8. php判断数组某个值是否存在
  9. php生成一个不重复的会员号
  10. tideways+toolkit对php代码进行性能分析