如何使用Jquery选择带有事件属性的元素?

9
希望有一个简单的解决方法。 我想选择所有具有事件属性的html元素。例如:onclick,onkeypress等。是否有一种使用Jquery最简单的方法,而不是分别选择每个属性? 谢谢

令人惊讶的是,到目前为止给出的答案都没有回答你有趣的问题。 - gdoron
4个回答

4

我相信简短的回答是

不同的HTML标签支持不同的事件,因此它们应该在jQuery代码中某个地方硬编码。通读jQuery代码,我找不到任何关于onkeypress事件的参考,例如。

因此,我认为您可以只依赖Has Attribute Selector[attribute]

$('[onclick], [onkeypress], [etc]');

1

如果值不是特定的,您可以尝试这种方法

以下演示基于$([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());
});

这个回答如何解决问题? - gdoron
gdoron是正确的。他想知道是否有一种类似于:hasEvent选择器,而不是列出所有事件的方法。 - Luca Fagioli

1
您可以编写一个自定义过滤函数来查找具有以 on 开头的属性的元素,如下所示:
$.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');
});

只有在您仅使用标准HTML属性时,这才是安全的。 - Luca Fagioli
@LucaFagioli 是的,我只是试图添加另一种解决 OP 问题的可能性。我理解对于他的情况,事件是通过标准 HTML 属性连接的。OP 更了解他的 HTML 模板,他会知道我的解决方案是否对他的特定情况有用,我只是在提供不同的解决方案 :-) - Nelson
这是一种弱检查。虽然它具有正确的语法(仅在标准HTML属性的上下文中),但不同的HTML标签仅支持此类事件的子集。您还应该针对映射[tag :: [attributes]]添加检查。但我认为这开始变得太耗CPU了。 - Luca Fagioli
个人认为你的解决方案并不是一个坏的解决方案,我只是试图提出建设性的批评 :) - Luca Fagioli
谢谢你的反馈,建设性的批评总是受欢迎的 :-) - Nelson
@Nelson 谢谢你提供的解决方案。在我的情况下,我无法保证此脚本运行的HTML仅具有标准属性。无论如何,尝试得很好。感谢你的努力。 :) - user1408470

0

你可以解析所有元素并进行检查。虽然不是很高效,但应该可以工作。

检查获取所有带有onclick的元素?

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] );
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接