我有一个 html 特殊字符,我想像复选框一样打开和关闭。在本例中,它是一颗星:☆,可以填充:★。
我想检查点击时星星的状态。
$(".action_table_star").click(function() {
if ($(this).html() == "★") {
$(this).html("☆");
$(this).css('color', 'white');
} else {
$(this).html("★");
$(this).css('color', 'rgb(255,165,0)');
}
});
但这不起作用,因为 $(this).html() 永远不等于“★”。我怎样才能重写这个if语句来解码html特殊字符并检查它的“状态”?
最佳答案
不要使用 .html()
,而是将 .text()
与 \uxxxx
序列结合使用,或 String.fromCharCode()
.
$(".action_table_star").click(function() {
if ($(this).text() == String.fromCharCode(9733)) {
$(this).html("☆");
$(this).css('color', 'white');
} else {
$(this).html("★");
$(this).css('color', 'rgb(255,165,0)');
}
});
当使用\uxxxx
方法时,您必须将base-10数字charcode转换为base-16数字charcode。示例(在控制台中):
(9734).toString(16);
// Returns 2606. Now, paste `"\u2606"` in your code
不要忘记填充足够的零以获得 4 位数字。
关于jquery - 使用 jQuery 检查文本是否等于 html 特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9844756/