简体   繁体   English

Jquery,检查charAt()是否等于unicode字符?

[英]Jquery, check if charAt() is equal to a unicode character?

I've got a collapsible link which has the unicode arrow on it 我有一个可折叠的链接,上面有unicode箭头

►This is a collapsible link

And when someone clicks on it I want it to be turned into the down arrow ▼. 当有人点击它时,我希望它变成向下箭头▼。 However I am having trouble figuring out how to parse to replace this character. 但是我无法弄清楚如何解析替换这个角色。

Here is my code: 这是我的代码:

function CollapsibleContainerTitleClickApp(){
     $(".collapsibleContainerContent.app", $(this).parent()).slideToggle();
     alert($(this).text().trim().charAt(0));
     if ($(this).text.trim().charAt(0) == "\u25B8"{
        alert("inside the if statement");
        $(this).text($(this).text().replace("\u25B8", "\u25BE"));
     }else{
        $(this).text($(this).text().replace("\u25BE", "\u25B8"));
}

Now the first alert always pops up as the actual arrow (►) and viewing the source also has the actual arrow. 现在,第一个警报总是弹出,因为实际箭头(►)和查看源也有实际箭头。 How can I see if the first character is one arrow, and if so replace it with the other arrow? 如何查看第一个字符是否为一个箭头,如果是,请将其替换为另一个箭头? The second alert statement never fires so it's never passing the condition of the if. 第二个警告语句永远不会触发,因此它永远不会传递if的条件。

You have multiple errors in your if statement, this is why that branch is never hit. if语句中有多个错误,这就是永远不会命中该分支的原因。

if ($(this).text.trim().charAt(0) == "\u25B8"{

You forgot the closing ) of the if statement. 你忘了关闭)中的if语句。

Also, you're not invoking the text() method, you're trying to access it as a member, which it isn't. 此外,您没有调用text()方法,而是尝试将其作为成员访问,而不是。

Your code should look like this: 您的代码应如下所示:

if ($(this).text().trim().charAt(0) == "\u25B8") {

You can solve this with css and jQuery, too: 您也可以使用css和jQuery解决这个问题:

CSS: CSS:

.collapsible_link:before { content: "\25BC"; }
.collapsed_link:before { content: "\25BA"; }

jQuery: jQuery的:

$('#link').click(function(o) {
   $(o).toggleClass('collapsible_link collapsed_link');
});

charCodeAt(index) returns the integer unicode value of the character at the specified index. charCodeAt(index)返回指定索引处字符的整数unicode值。 This is often the easiest way to test individual char values -- especially when they're non-printable, or special in some other way. 这通常是测试单个char值的最简单方法 - 尤其是当它们不可打印时,或者以其他方式特殊时。 (docs at w3schools) (w3schools的文档)

Also... be sure you're comparing the correct unicode values. 另外......请确保您正在比较正确的unicode值。 "\▸" is the "small right arrow" ( ) -- but the arrow you showed in your example is the "large right arrow", which is "\►" ( ) "\▸"是“小右箭头”( ) - 但您在示例中显示的箭头是“大右箭头”,即"\►"

so... a simple example using charCodeAt() and the correct unicode value: 所以...使用charCodeAt() 正确的unicode值的简单示例:

var s = "►This is a collapsible link";
if(s.charCodeAt(0) === 0x25BA) {
   alert( "true!");
}

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

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