【问题标题】:how to add classname to all elements starting with specific id?如何将类名添加到以特定 id 开头的所有元素?
【发布时间】:2020-02-20 13:34:28
【问题描述】:

在你抨击我之前,我知道这个问题可能是重复的。 我尝试了在 stackoverflow 上找到的所有其他帖子,但都失败了。

我想为我的 html 中以“子类”开头的所有元素添加一个类名,后跟一个数字(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>

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

【问题讨论】:

  • 您的引号在您尝试连接 classid 的位置不匹配。我建议使用带有语法突出显示的编辑器,因为它几乎不可能出现这样的错误。
  • 更正引号,变量“classid”附近的引号不正确,因为文本不正确,它会将其视为字符串。 $("p[id^='subclass" + classid + "']").addClass('bold');试试上面的代码

标签: javascript jquery jquery-selectors


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2013-05-15
    • 1970-01-01
    • 2022-08-23
    • 2012-11-01
    • 2022-07-21
    相关资源
    最近更新 更多