有没有一种方法可以用jquery更改类的属性

Is there a way to change the property of a class with jquery?

本文关键字:jquery 属性 方法 一种 有没有      更新时间:2024-05-21

这个问题可能重复或愚蠢。我读过类似的问题,但不是这个确切的问题。

假设我有两个动态生成的li,它们的类为.someclass.someclass2,并且都有不同的宽度,需要在页面加载时进行计算。

那么,有没有一种方法可以将计算的宽度设置为类一次,而不是每次生成新的li时都设置宽度

我们可以用css来做这件事,如果宽度是已知的,.someclass { width: 20px;} .someclass2 { width: 50px;},然后每当一个新元素生成时,css就会应用到它们。

每次发生追加时应用宽度

$('#somediv').click(somefunction);
function somefunction() {
    $('#somediv').append('<li class="someclass"><li class="someclass2"></li></li>');
    $('.someclass').css('width', $(document).width() - 112); //every time
    $('.someclass2').css('width', $(document).width() - 250);  //every time
}

应用宽度一次-有办法只应用一次吗?

$('.someclass').css('width', $(document).width() - 112);  //once, but it will not work
$('.someclass2').css('width', $(document).width() - 250);  //once, but it will not work
$('#somediv').click(somefunction);
function somefunction() {
  $('#somediv').append('<li class="someclass"><li class="someclass2"></li></li>');
}   

如果有更多的元素,并且这种情况经常发生,会有什么性能差异吗?

这里我们可以使用JS创建一个cssText,因此我们可以为每个css类设置自定义值。

然后创建一个style元素,并将其内容设置为预定义的cssText

var cssText = '.someClass {width:' + (window.innerWidth - 100) + 'px;} .someClass2 {width:' + (window.innerWidth - 200) + 'px; }',
    head = document.head,
    style = document.createElement('style');
if (style.styleSheet){
    style.styleSheet.cssText = cssText;
} else {
    style.appendChild(document.createTextNode(cssText));
}
head.appendChild(style);

现在所有你需要做的:

  • 运行上面的代码来创建所需的类
  • 随时调用代码,而无需每次添加css样式