jQuery – 根据前缀获取元素类

从下面元素中的类中获取“淡入淡出”字符串的最快方法是什么?

...

 var classes = $('.MyElement').attr('class').split(' '); for (var i = 0; i < classes.length; i++) { var matches = /^fx\-(.+)/.exec(classes[i]); if (matches != null) { var fxclass = matches[1]; } } 

如果你想寻找以’淡入淡出’结尾的东西,你会使用:

 $("*[class$='fade']") 

对于以“淡入淡出”开头的类的元素,您将使用:

 $("*[class^='fade']") 

并且要获得包含’fade’的元素,你会使用(这比通过类名字符串更快)

 $("*[class*='fade']") 

“*”获取所有元素,因此您可以将其替换为您想要的元素。

如果你想要一个类名以’fx-‘开头的元素你会这样做:

 var classname = ""; var elArray = $("*[class*='fx-']"); for (var a= 0; a < elArray .length; a++) { //fade classname = elArray[a].split("-")[1]; } 

for循环中使用的数组将具有类名为'fx-'的所有元素。

而不是for循环检查元素的正确类名。

有关更多信息,请访问jquery.com

试试这个:

 $("div[class*='fade']") 

更多信息

查看JQuery选择器正则表达式 。 它可能正是您所需要的! 🙂

我可能会选择以下内容:

 //Split class list into individual classes: var classes = $(".MyElement").attr("class").split(" "); var fxType; //Loop through them: for (var i = 0, max = classes.elngth; i < max; i++) { var class = classes[i].split("-"); //Check if the current one is prefixed with 'fx': if (class[0] == "fx") { //It is an FX - do whatever you want with it, the type of FX is stored in class[1], ie: fxType = class[1]; } } 

我们在网站中使用的这个简单代码段:

 /** * Script to load a popup container for share buttons * * Possible usage for Facebook, Twitter and Google: * *  *  *  */ jQuery(document).ready(function ($) { // Whenever an anchor with the class with share-button in it is clicked $("a[class*='share-button']").click(function () { // Variables to set the size of the popup container var windowWidth = 500; var windowHeight = 255; // Variables to set the position of the popup container var positionWindowLeft = (screen.width / 2) - (windowWidth / 2); var positionWindowTop = (screen.height / 3) - (windowHeight / 3); // Create new windows with the opening url of the href attribute of the anchor and the above variables var popupWindow = window.open($(this).prop('href'), '', 'scrollbars=no,menubar=no,status=no,titlebar=no,toolbar=nolocation=no,menubar=no,resizable=noe,height=' + windowHeight + ',width=' + windowWidth + ',top=' + positionWindowTop + ', left=' + positionWindowLeft); // If the default windows is focused if (window.focus) { // Change the focus to the the popup window popupWindow.focus(); } return false; }); });