javascript jQuery。选择所有以 classname 开头的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5411888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:06:38  来源:igfitidea点击:

jQuery. Select all the elements that classname starts with

javascriptjquery

提问by iLemming

If I have elements with classnames like this:

如果我有这样的类名的元素:

   .ses_0 .ses_1 .ses_2 .ses_3  

How can I select all the elements and prepend those with some snippet? Something like this:

如何选择所有元素并在这些元素之前添加一些片段?像这样的东西:

    var sessions = $('*[class*=ses_]');

    for (var i = 0; i < sessions.length; i++)
    {
        sessions [i].prepend("<img src='/Content/img/caticon"+i+".png' />");
    }

That doesn't work of course.

那当然行不通。

Edit:Ahhhh... damn It seems that I need to get not only those classes that start with .ses_ but also <a>elements within. How can I do that?

编辑:啊哈...该死的 看来我不仅需要获取以 .ses_ 开头的那些类,还需要获取其中的 <a>元素。我怎样才能做到这一点?

Basically something that works $(".ses_0 a"), only I need to get all the classes start with ses_

基本上是$(".ses_0 a")可行的,只有我需要让所有的类都以 ses_ 开头

回答by typeof

You're almost there:

你快到了:

// selects all that start with "ses_"
var sessions = $('[class^="ses_"]');

Even though your loop should work, you could also use the

即使你的循环应该工作,你也可以使用

sessions.each(function(index){
    this.prepend(... // and so on
});

回答by Oscar

You can use the attribute starts with selector in jQuery: http://api.jquery.com/attribute-starts-with-selector/

您可以在 jQuery 中使用以选择器开头的属性:http: //api.jquery.com/attribute-starts-with-selector/

Beware that it's not nearly as fast as using the regular way of selecting elements.

请注意,它不如使用常规选择元素的方式快。