如何查看以?结尾的课程?

我有一些元素,如:

Elem1
Elem2
Elem3
Elem4

和处理程序:

 $('.button').click(function () { }); 

在这个处理程序中,我需要做一些特殊的操作,比如为具有-dashboard-check完成的类的元素推断NN和SOCIAL。

例如,如果我点击Elem4,就不会发生任何事情。 如果我点击Elem1我需要打印17和facebook,两个变量都不同。

在jquery上执行此操作的快速方法是什么? 正则表达式? .HasClass以?结尾?

假设您可以控制HTML,那么最好使用HTML data-属性将此信息嵌入到:

 
Elem1
Elem2
Elem3
Elem4

现在很容易编写仅适用于您想要的元素的选择器:

 $('.button[data-id][data-service]').click(...); 

并且非常容易获得您点击所需的信息:

 $('.button[data-id][data-service]').click(function() { alert($(this).attr("data-id")); // with jQuery alert(this.getAttribute("data-service")); // without jQuery }); 

使用以选择器结束

  $( "div[class$='-dashboard-check']" ).each(function( index ) { console.log( index + ": " + $( this ).attr("id") ); }); 

尝试使用endswith属性选择器:

 $("[attribute$='value']") 

 $("[class$='-dashboard-check']") 

你需要*=

描述:选择具有指定属性的元素,其值包含给定的子字符串。

尝试:

 $( "div[class*='-dashboard-check']" ) 

$ = check string以。结尾
* =检查字符串包含

这是属性选择器的完整列表

您可以使用[attribute $ = value] CSS选择器: http : //www.w3schools.com/cssref/sel_attr_end.asp 。 类似的东西:[class$=endVal]

尝试

 (function () { $.fn.hasClassEndsWith = function (suffix) { if (this.length === 0) { return false; } var clazz = this.attr('class'); if (clazz === undefined) { return false; } var classes = clazz.split(' '); var regex = new RegExp(suffix + '$', 'i'); for (var i = 0; i < classes.length; i++) { if (regex.test(classes[i])) { return true; } } return false; }; })(jQuery); jQuery(function () { $('.button').click(function () { if ($(this).hasClassEndsWith('dashboard-check')) { console.log('dashboard') } else { console.log('normal') } }); }) 

演示: 小提琴

  
Elem1
Elem2
Elem3
Elem4

试试这个:

  $( "div[class$='-dashboard-check']" ).click(function (e) { var o = $(e.target) var str = o.attr('class'); var s1 = str.substring(7,9); var s2 = str.substr(10,str.indexOf('-')); alert(s1+" "+s2); });