如何将类名添加到以特定ID开头的所有元素?

Ebe*_*aac 1 javascript jquery jquery-selectors

在您对我提出批评之前,我知道这个问题可能是重复的。我尝试了在stackoverflow上发现的所有其他帖子,但均失败了。

我想给我的html中所有以'subclass'开头的元素添加一个类名,然后是一个数字(classid),然后是一个随机数。我不完全知道有多少元素,因为它是通过servlet动态生成的。

以下是我尝试运行的代码:

<style>
.bold {
    font-weight: bold;
}
</style>
<script>
function highlight(classid){
    alert(classid);
    $("p[id^='subclass'+classid]").addClass('bold');
    alert('hello world');
}
</script>
<p id='subclass25'>Hello World </p>
Run Code Online (Sandbox Code Playgroud)

我收到classid的警报,但没有收到“ hello world”的警报。所以我可以肯定我的JQuery是错误的...。

Bhu*_*kar 5

您错过了引号,这是无法正确创建jquery选择器的原因,请参见下文

 highlight('25');
 function highlight(classid){
        alert(classid);
        $("p[id^='subclass" + classid + "']").addClass('bold');
        alert('hello world');
    }
Run Code Online (Sandbox Code Playgroud)
.bold {
    font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='subclass25'>Hello World </p>
Run Code Online (Sandbox Code Playgroud)