如何获取以给定字符串开头的特定类的元素?

新手上路,请多包涵

我有一个包含多个类的元素列表,例如:

 <input class="etape btn-info others">
<input class="etape btn-inverse others">
<input class="etape btn-danger others">

如何编写允许我执行以下操作的 jQuery 代码……

 $(".etape").click(function(){
   $(this).get("the class that starts with btn-")
   // in order to store this value in a variable to reuse it later
});

原文由 fatiDev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 293
2 个回答

您可以使用正则表达式或 split 类名。

 $(".etape").click(function(){
   var classes = $.grep(this.className.split(" "), function(v, i){
       return v.indexOf('btn') === 0;
   }).join();
});

http://jsfiddle.net/LQPh6/

原文由 Ram 发布,翻译遵循 CC BY-SA 3.0 许可协议

您也可以尝试:

 $(".etape").click(function () {
    var theClass = $(this).attr("class").match(/btn[\w-]*\b/);
    console.log(theClass);
});

使用 match 而不是 grep …

原文由 Marc Audet 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题