如果属性等于某个值,则目标 HTML 元素 [英] Target HTML element if attribute equals a certain value
问题描述
我有一个 HTML
模板字符串,它为 Ajax
前置 一些用户信息到 div
> 打电话.每个 div
都有一个带有 false
或 true
值的 data-stream
属性.
I have an HTML
template string that prepends
some user info to a div
for each user from an Ajax
call. Each div
has a data-stream
attribute with either false
or true
values.
我想使用 JS
或 jQuery
定位 element
并使用 CSS
或 addClass
如果 value
为真.
I want to target the element
using JS
or jQuery
and use CSS
or addClass
on it if the value
is true.
如果值为 true,可能会显示一个绿色图标,如果值为 false,则可能会显示一个红色图标.
Maybe display a green icon if the value is true and a red one if false.
JS
var target = $('#result')
target.prepend('<div data-stream="' + userObj.stream + '" class="item "> <a target="_blank" href="' + userObj.url + '"> <img class="logo" src="' + userObj.logo + '"/> <span class="name">' + userObj.name + '</span> </a> </div>')
我的尝试
if ( typeof $(".item").attr('data-stream') === "true" ) {
// style div here..
}
这不起作用,也不行:
$('.item').filter(function(){
var $this = $(this)
return $this.data('data-stream') === true
}).addClass('online')
也不:
$("#results .item").find("[data-stream='true']")
必须有一个非常简单的方法来做到这一点,使用 jQuery 或 JS 有什么建议吗?
There has got to be a pretty simple way to do this, any suggestions using jQuery or JS ?
推荐答案
您的 $("#results .item").find("[data-stream='true']")
是非常接近,但它会寻找具有该属性的项目作为 .item
元素的 后代.您想查找 自身 具有该属性和值的 .item
元素:
Your $("#results .item").find("[data-stream='true']")
was really close, but it looks for items with that attribute as descendants of the .item
elements. You want to look for .item
elements that themselves have that attribute and value:
$("#results .item[data-stream='true']")
注意 .item
和 [data-stream='true']
之间没有空格.这是一个复合选择器.
Note no space between .item
and [data-stream='true']
. It's a compound selector.
或者如果你有理由像你的find
那样分开做它们,使用filter
而不是find
(但前提是你有理由将这两个方面分开):
Or if you have reason to do them separately as with your find
, use filter
rather than find
(but only if you have a reason to separate the two aspects):
// If you have reason to separate the two aspects
$("#results .item").filter("[data-stream='true']")
复合选择器的实例:
var target = $('#result')
target.prepend('<div data-stream="true" class="item ">This is the true one</div>');
target.prepend('<div data-stream="false" class="item ">This is the false one</div>');
console.log("Turning the true one blue with a class");
$("#result .item[data-stream='true']").addClass("foo");
.foo {
color: blue;
}
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
旁注:您的部分问题使用 id
result
,其他部分使用 results
.你会希望这些匹配.
Side note: Part of your question uses the id
result
, and other parts use results
. You'll want those to match.
这篇关于如果属性等于某个值,则目标 HTML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!