使用jQuery通过样式选择元素 [英] Using jquery to select an element by it's style

查看:118
本文介绍了使用jQuery通过样式选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图选择一个没有类或ID的html元素,但是我仍然需要选择它.这是元素的样子:

I am trying to select an html element that has no classes or id's, but I still need to select it. Here is what the element looks like:

    <table style="background-color: white; border: 1px solid #aaa; 
    box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid 
    #1E90FF; margin: 0 auto;" class="">

我试图制作一个具有以下元素的选择器:

I tried to make a selector that got the element like this:

    $("table[style~='background-color: white; border: 1px solid #aaa;
    box-shadow: 2px 2px 2px rgba(0,0,0,0.2); border-left: 10px solid 
    #1E90FF; margin: 0 auto;']")

但是它不起作用.有人可以帮我吗?

But it doesn't work. Can someone help me out with this?

推荐答案

选择器是错误的,您缺少一些空格.

The selector is just wrong, you are missing some spaces.

您可以使用 属性选择器 style的jQuery中,但请记住,如果另一个JavaScript函数影响元素样式,则选择器将不起作用.

You can use the attribute selector in jQuery for style but have in mind that an inline-style can change if another javascript function affects the element style the selector will not work.

寻找另一个选择器要好得多,寻找包装表元素的类或ID.

Looking for another selector is much better, look for a class or an id wrapping the table element.

如果有,请执行以下操作:

If there is, do something like this:

.el table {}
OR
#el table {}


使用属性选择器:


Using Attribute selector:

console.log($('table[style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"]').length);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"></table>

使用> filter() 方法

console.log($('table').filter('[style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"]').length);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="background-color: white; border: 1px solid #aaa; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); border-left: 10px solid #1E90FF; margin: 0 auto;"></table>

这篇关于使用jQuery通过样式选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆