gpt4 book ai didi

javascript - jQuery 选择器 : 'starts-with && ends-with' doesnt work on element with multiple classes

转载 作者:行者123 更新时间:2023-12-03 07:38:17 24 4
gpt4 key购买 nike

问题如下,当我尝试选择一个以关键字开头并以另一个关键字结尾的类时,当且仅当元素具有单个类时,这才可以正常工作,如果元素具有多个类,选择器将返回一个空集合。

这是解释问题的代码

// try removing custom-class from first element --> returns 2

alert($("div[class^='start'][class*='end']").length) // will return 1 by default , only 1 element has single class.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-class start-mid-end" data-custom="1st Div">

</div>
<div class="start-mid-end" data-custom="2nd Div">

</div>

最佳答案

这是因为对于 class="custom-class start-mid-end" 的元素,其 class 属性的值以 custom,而不是开始。请记住,属性选择器将属性值作为单个字符串进行操作;他们不关心 class 属性在 HTML 中是否“特殊”。

关于您的问题的解决方案:没有任何解决方案是没有警告的。作为最实用的解决方法,我建议使用多个类而不是仅一个类。例如,不仅要添加 prefix-X-suffix 类,还要添加 prefix- -suffix 类,然后您只需使用

即可选择元素
$("div[.prefix-.-suffix]")

另一种选择是使用filter来自定义类选择逻辑,例如

$("div").filter(function() { return /\bstart\S*end\b/.test(this.className); })

正则表达式 \bstart\S*end\b 匹配具有前缀 start 和后缀 end 的任何非空白字符序列,这就是您所追求的。

关于javascript - jQuery 选择器 : 'starts-with && ends-with' doesnt work on element with multiple classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com