希望有一个简单的解决方法。
我想选择所有具有事件属性的html元素。例如:onclick,onkeypress等。是否有一种使用Jquery最简单的方法,而不是分别选择每个属性?
谢谢
我相信简短的回答是不。
不同的HTML标签支持不同的事件,因此它们应该在jQuery代码中某个地方硬编码。通读jQuery代码,我找不到任何关于onkeypress事件的参考,例如。
因此,我认为您可以只依赖Has Attribute Selector[attribute]
:
$('[onclick], [onkeypress], [etc]');
如果值不是特定的,您可以尝试这种方法。
以下演示基于$([attr1],[attr2],...,[attrN])
选择器打印"hey you people":
<div class="container">
<div>no id</div>
<div id="a">hey</div>
<span name="b">you</span>
<p id="c">guys</p>
</div>
$('[id],[name]').each(function(){
console.log($(this).text());
});
基于这个结构,可以编写简单的包装器:
$.fn.hasAttrib = function() {
var attributes = [];
$.each(arguments, function(index, value){
attributes.push('[' + value + ']');
});
return $(this).find(attributes.join());
};
在下面的语句中使用这样的插件也会打印出"嘿,你们人":
$('.container').hasAttrib('id','name').each(function(){
console.log($(this).text());
});
$.fn.filterOn = function() {
this.each(function(ind,el) {
var attrs = el.attributes;
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].nodeName.indexOf('on') === 0) return true;
}
return false;
});
};
并像这样使用它:
//elems will contain all input fields with an attribute starting with 'on'
elems = $(':input').filterOn();
这将返回页面中所有具有以on开头的属性的元素(使用*选择器时要注意性能):
$("*").filterOn().each(function() {
console.log('Element '+this.tagName + ' has an on... attribute');
});
你可以解析所有元素并进行检查。虽然不是很高效,但应该可以工作。
var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
if ( allElements[i].className !== 'theClassNameYoureLookingFor' ) {
continue;
}
if ( typeof allElements[i].onclick === 'function' ) {
// do something with the element here
console.log( allElements[i] );
}
}