【发布时间】:2021-11-27 13:41:36
【问题描述】:
我想检查一个元素是否有 .active 类,如果确实添加:margin-top: 4px;
但是我只希望这种情况发生一次,当页面加载时,一旦检测到该类,我不想再次检测它并添加 CSS 样式。
当某些元素悬停时应用此类。
这在 jQuery 中可行吗?
【问题讨论】:
标签: jquery
我想检查一个元素是否有 .active 类,如果确实添加:margin-top: 4px;
但是我只希望这种情况发生一次,当页面加载时,一旦检测到该类,我不想再次检测它并添加 CSS 样式。
当某些元素悬停时应用此类。
这在 jQuery 中可行吗?
【问题讨论】:
标签: jquery
查看one 事件。记录示例:
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
【讨论】:
这将在页面加载时触发一次
$(function(){
if ($("#elementid").hasClass("active"))
{
$("#elementid").css("margin-top", "4px");
}
});
【讨论】:
我通常这样做的方式是:
(function($) {
// my custom function to process elements
function myProcessFunction(context) {
// get context
context = context || document;
// select elements within the context, filter out already processed ones
// loop through remained (unprocessed) elements
// '.my-class' - selector for the elements I want to process
$('.my-class:not(.my-class-processed)', context).each( function(i.e){
// mark the element as processed
$(e).addClass('my-class-processed');
// add process code here
});
}
// run myProcessFunction on document.ready
$(document).ready( function(){
myProcessFunction();
});
})(jQuery);
这样我就有了:
希望这会有所帮助)
【讨论】: