【问题标题】:Issue with "+" character on varvar 上的“+”字符问题
【发布时间】:2019-04-25 10:57:52
【问题描述】:

我对传递给 jQuery 对象 $() 的字符串中的字符“+”有疑问

我尝试初始化String对象和concat,但问题依旧。

function fn(string){
    $(string).show();
}

let myString = ".my-class-that-contains+";
fn(myString);

代码未按预期响应。当我从字符串末尾删除字符“+”时,一切正常。

【问题讨论】:

  • The code doesn't response as expected -- 期望是什么,它与响应有何不同?
  • 这是做什么的?因为$("You need to know about c++") 不应该匹配任何东西。
  • $(string).show();没有意义

标签: javascript jquery string-concatenation


【解决方案1】:

+ 在选择器中具有定义的含义。这是一个sibling combinator

要在类选择器的类名中使用它,您需要对其进行转义(使用\)。

请记住,CSS 转义字符也是 JavaScript 转义字符,因此您必须对选择器中的 \ 字符进行转义才能将它们放入 JavaScript 字符串文字中。

function fn(string){
    $(string).show();
}

let myString = ".my-class-that-contains\\+";
fn(myString);
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="my-class-that-contains+">
This is hidden by default
</div>

最好一开始就避免在类名中使用特殊字符。

【讨论】:

【解决方案2】:

你可以使用like选择器。

  function fn(string){
    // $(string).show();

    $('[class="'+string+'"]').show();
    }

    let myString = ".my-class-that-contains+";
    fn(myString);

供参考: https://api.jquery.com/attribute-starts-with-selector/

【讨论】:

    猜你喜欢
    • 2016-09-09
    • 2022-11-20
    • 1970-01-01
    • 2012-03-14
    • 2014-02-23
    • 2017-03-07
    • 2022-01-01
    • 2013-08-13
    • 2011-01-11
    相关资源
    最近更新 更多