【问题标题】:$("span").each() not working when I do .css() on iterated element当我对迭代元素执行 .css() 时,$("span").each() 不起作用
【发布时间】:2021-03-03 23:58:45
【问题描述】:

我有一个代码,我在其中迭代元素,我想获得每个元素的 css 样式。 我得到这个错误指的是.each:

Uncaught TypeError: Cannot read property 'replace' of undefined

示例代码如下:

  $("span").each(function(i,v){
   test($(this));
 })

 function test(element){
  console.log(element.css());  //not working
  console.log($(element).css()); //not working either
 }

【问题讨论】:

  • 我做到了。当我不知道所有可能的规则时,我只想获得所有样式

标签: jquery css each


【解决方案1】:

.css 需要一个参数:要么传递一个参数,一个属性名称,以检索其值,要么传递两个参数,一个属性名称和将其设置为的值:

$("span").each(function(i, v) {
  test($(this));
})

function test(element) {
  console.log(element.css('color'));
}


$("span").each(function(i, v) {
  test2($(this));
})

function test2(element) {
  element.css('color', 'yellow')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style="color: green">text</span>

$("span").each(function(i, v) {
  test($(this));
})

function test(element) {
  console.log(element.css()); //not working
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span></span>

如果你传递 no 个参数,jQuery 会抛出一个错误,因为它期望第一个参数是一个字符串。

如果你想使用所有属性访问底层 CSSStyleDeclaration,请使用 vanilla DOM 方法而不是 jQuery:

$("span").each(function(i, v) {
  console.log(this.style);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style="color: green">text</span>

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2022-01-10
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多