jQuery – 只做一次
我想检查一个元素是否具有类.active,如果它确实添加:margin-top:4px;
但是我只希望这种情况发生一次 ,当页面加载时,一旦检测到类,我不想再次检测它并添加CSS样式。
当某些元素hover在上面时,将应用此类。
这在jQuery中可行吗?
查看一个活动。 记录的例子:
$('#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(ie){ // mark the element as processed $(e).addClass('my-class-processed'); // add process code here }); } // run myProcessFunction on document.ready $(document).ready( function(){ myProcessFunction(); }); })(jQuery);
这样我有:
- 可重复使用的function
- 已标记处理的元素,下次调用该函数时将不会处理这些元素
- 如果指定了元素,则仅在上下文中处理(例如,通过AJAX请求返回的HTML代码)
希望这可以帮助 )