简体   繁体   English

如果 span 包含精确文本,则将 class 添加到页面上的某个元素

[英]If span contains exact text, add class to certain element on page

I have this code below.我在下面有这段代码。

    $("span.number").filter(function() {
    if (return ($(this).text() === 'PENDING')) {
        $(".property-thumb").addClass("pending");
    } 
    if (return ($(this).text() === 'PENDING INSPECTION')) {
        $(".property-thumb").addClass("pendinginspection");
    } 
});

Simply speaking, if "span.number" contains PENDING or PENDING INSPECTION, I want certain classes to be added to ".property-thumb".简单来说,如果“span.number”包含 PENDING 或 PENDING INSPECTION,我希望将某些类添加到“.property-thumb”。 Why isn't this working?为什么这不起作用?

You can't use the return keyword in an if statement.That is invalid syntax.您不能在if语句中使用return关键字。这是无效的语法。
Instead of filter use an each loop and remove the return statement.代替filter使用each循环并删除return语句。

In the loop get the select the current element being looped over with $(this) , find the parent in which it is in with parents() (this is to create a context of which thumbnail it should select), and select the thumbnail element from the parent with find() .在循环中获取 select 当前元素被$(this)循环,找到它所在的父元素parents() (这是创建它应该选择哪个缩略图的上下文),以及 select 缩略图元素来自带有find()的父级。

Check with each item in $("span.number") if the text is either PENDING or PENDING INSPECTION with an if...else if statement and then add the classes accordingly to the thumbnail.检查$("span.number")中的每个项目,如果文本是PENDINGPENDING INSPECTION并使用if...else if语句,然后将相应的类添加到缩略图中。

Tip: the $ before a variable can be a way to indicate that the value is a jQuery object so you know what kind of value it is and what you can do with it.提示:变量前的$可以表示该值是 jQuery object 以便您知道它是什么类型的值以及可以用它做什么。

$("span.number").each(function() {
  var $this = $(this);
  var text = $this.text();
  var $property = $this.parents('.property');
  var $propertyThumb = $property.find('.property-thumb');
  if (text === 'PENDING') {
    $propertyThumb.addClass("pending");
  } else if (text === 'PENDING INSPECTION') {
    $propertyThumb.addClass("pendinginspection");
  } 
}

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

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