JavaScript中endsWith()用法及排除特定后缀元素循环问题
问题解答
1. JavaScript中endsWith()函数的使用方法
- 基本语法:
str.endsWith(searchString[, length])str:需要检测的原字符串searchString:要匹配的后缀字符串length(可选):指定原字符串的检测长度,默认使用原字符串的实际长度
- 示例代码:
const demoStr = "JavaScript Guide"; console.log(demoStr.endsWith("Guide")); // 输出 true console.log(demoStr.endsWith("Script")); // 输出 false // 指定检测长度为10,相当于只检测前10个字符是否以"Script"结尾 console.log(demoStr.endsWith("Script", 10)); // 输出 true
2. 过滤以':yazma'结尾的元素避免jQuery选择器错误
你的问题是因为当键(或拆分后的子键)以:yazma结尾时,jQuery会将:yazma识别为不支持的伪类选择器,从而触发语法错误。只需在循环中过滤掉这些键即可解决:
修改后的代码:
if (!izinler.TASINMAZ_YONETICI) { for (var ad in Ayarlar.module_adlari) { if (!izinler[ad]) { var adlar = ad.split(","); adlar.forEach(function(a) { // 跳过以':yazma'结尾的子键 if (!a.endsWith(':yazma')) { $("." + a) .parent() .remove(); } }); } } }
说明:
通过a.endsWith(':yazma')判断当前子键是否符合排除条件,符合则跳过DOM操作,避免生成包含:yazma的错误选择器。
内容的提问来源于stack exchange,提问作者babyFrontendDeveloper
相关产品推荐
相关产品推荐

