简体   繁体   English

jQuery:对页面上的每个元素执行相同的操作

[英]jQuery : Perform same action for each element on a page

I have read so many related questions, the list is given below but none seems to be applicable in my situation. 我已经阅读了很多相关问题,下面列出了这些问题,但似乎没有一个适用于我的情况。

I want that a border should appear around the element. 我希望在元素周围出现边框。 I have tried the below code but $("*") selects all the elements in the hierarchy, and the border appears around parent elements as well, which is not what I want. 我试过下面的代码,但是$(“ *”)选择层次结构中的所有元素,并且边框也出现在父元素周围,这不是我想要的。 I want to select only the clicked element, and NOT THE PARENT ELEMENTS. 我只想选择单击的元素,而不要选择父元素。

Here is the script 这是脚本

$( "*" ).each(function(){ 
    $(this).on( "mousedown", function(){
        $(this).css("border", "1px solid red");
    }); 

$(this).on( "mouseup", function(){
        $(this).css("border-style", "none");
    });
});

Here goes a list of some of my 'not so useful' research: - javascript - Best Way to Get All DOM Elements with jQuery 这里列出了一些我的“不太有用”的研究: -JavaScript-使用jQuery获取所有DOM元素的最佳方法

jquery get all form elements: input, textarea & select jQuery获取所有表单元素:input,textarea和select

All Selector (“*”) | 所有选择器(“ *”)| jQuery API Documentation jQuery API文档

Using the * selector is incredibly inefficient as it adds an event handler to every element in the DOM. 使用*选择器的效率极低,因为它将事件处理程序添加到DOM中的每个元素。 You could use event propagation to do this instead by placing the event handler on the document and referencing the element which triggered the event using the target property. 通过将事件处理程序放在document上,并使用target属性引用触发事件的元素,可以使用事件传播来执行此操作。 Try this: 尝试这个:

$(document).mousedown(function(e) {
    $(e.target).css('border', '1px solid red');
}).mouseup(function(e) {
    $(e.target).css('border', '0');
});

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM