简体   繁体   English

jQuery-通过“样式”属性中的自定义CSS键查找元素的最佳方法

[英]jQuery - Best way to find elements by a custom CSS key in their “style” attribute

I have got a page where some elements have a fake CSS property called "key" like this : 我有一个页面,其中某些元素具有伪造的CSS属性,称为“ key”,如下所示:

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

I want to find these elements by their key. 我想通过它们的关键找到这些元素。 I have come up with this : 我想出了这个:

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;
}

I guess there are faster/better ways to do that ? 我猜有更快/更好的方法吗?

You can use like this 你可以这样使用

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

 });

This will return all elements which contains the style attribute key 这将返回所有包含样式属性key元素

Edit 编辑

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

You can go like this: 您可以像这样去:

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

The document is here : http://api.jquery.com/attribute-contains-selector/ 该文档位于此处: http : //api.jquery.com/attribute-contains-selector/

You can use something like this i think 我想你可以用这样的东西

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

usually we can get any css property using this 通常我们可以使用此获取任何CSS属性

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

so that may work out for you. 这样可以为您解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM