简体   繁体   English

jQuery和CSS选择器

[英]jQuery and CSS selectors

In the past I used the following code to take the take the text in the data-placeholder attribute and use it as a placeholder text for my div. 在过去,我使用以下代码来获取data-placeholder属性中的文本,并将其用作div的占位符文本。

[contentEditable=true]:empty:not(:focus):before {
    content:attr(data-placeholder)
}

This worked great, but in my current project we need to do the same thing except it's entirely built using jQuery. 这很好用,但在我目前的项目中我们需要做同样的事情,除了它完全使用jQuery构建。 I know jQuery has .empty() , .before() , :not() , and .focus() functions. 我知道jQuery有.empty() .before() .empty() .before() :not().focus()函数。 With the way the jQuery selectors work, is it possible to use the CSS selector in the jQuery selector like so? 通过jQuery选择器的工作方式,是否可以在jQuery选择器中使用CSS选择器?

var div = $([contentEditable=true]:empty:not(:focus):before);

If not, then is there a better way to do this when working with so many functions? 如果没有,那么在使用这么多功能时有更好​​的方法吗?

Simple solution is to append a style tag: 简单的解决方案是附加样式标记:

var rule ='[contentEditable=true]:empty:not(:focus):before {'+
   ' content:attr(data-placeholder)'+
'}';
$('head').append('<style>'+rule +'</style>');

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

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