jQuery -通过自定义的CSS键来查找元素的最佳方式.属性

jQuery - Best way to find elements by a custom CSS key in their "style" attribute

本文关键字:元素 查找 最佳 属性 方式 -通 自定义 CSS jQuery      更新时间:2023-09-26

我有一个页面,其中一些元素有一个假的CSS属性名为"key",像这样:

<div style="color:red;key:settings.color;background-color:violet;key:settings.bkgColor;"> 
</div>

我想通过键找到这些元素。我想到了这个:

function getElsByCssKey(){
    var foundEls = [];
    var style;
    $( "*" ).each(function(){
        style = $(this).attr("style");
        if(typeof style !== "undefined" && style.indexOf("key") !=- 1){
            foundEls.push(this);
        }
    })
    return foundEls;
}

我想有更快/更好的方法来做到这一点?

可以这样使用

$("[style*='key']").each(function(){
 });

这将返回所有包含样式属性key

的元素

编辑

 $("[style*='key:listColor']").each(function(){
   alert($(this).attr("style"));    
  });

你可以这样写:

$("[style*='key']").each(function(){
    foundEls.push($(this));
});

文档在这里:http://api.jquery.com/attribute-contains-selector/

你可以这样写

var key = $( this ).css( "key" ); 

通常我们可以使用这个

获取任何CSS属性
var color= $( this ).css( "color" );

所以这可能对你有用。