jQuery技术

jQuery 中的 39 个技巧 码农网(3)

字号+ 作者:H5之家 来源:H5之家 2017-03-20 08:00 我要评论( )

我们已经习惯了把我们所有的代码都放在ready的事件处理程序中,但是,如果你的html页面很庞大,decument ready恐怕会被延迟了,所以对于一些我们不希望ready后才可以触发的事件可以放在html的head元素中。 script//

我们已经习惯了把我们所有的代码都放在ready的事件处理程序中,但是,如果你的html页面很庞大,decument ready恐怕会被延迟了,所以对于一些我们不希望ready后才可以触发的事件可以放在html的head元素中。

<script> // jQuery is loaded at this point. We can use // event delegation right away to bind events // even before $(document).ready: $(document).on('click', '#clickMe', function(){ alert('Hit view source and see how this is made'); }); $(document).ready(function(){ // This is where you would usually bind event handlers, // but as we are using delegation, there is no need to. // $('#clickMe').click(function(){ alert('Hey!'); }); }); // Note: You should place your script tags at the bottom of the page. // I have included them in the head only to demonstrate that we can bind // events before document ready and before the elements are created. </script> 24.当使用js给多个元素添加样式时更好的做法是创建一个style元素。

我们之前提到过,操作dom是非常慢的,所以当添加多个元素的样式时创建一个style元素并添加到document中是更好的做法。

<ul> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> </ul> var style = $('<style>'); // Try commenting out this line, or change the color: style.text('#testList li{ color:red;}'); // Placing it before the result section so it affects the elements style.prependTo('#result'); 25.给html元素分配一个名为JS的class。

现代的web apps非常的依赖js,这里的一个技巧就是只有当js可用时才能显示特定的元素。看下面的代码。

$(document).ready(function(){ $('html').addClass('JS'); }); html.JS #message { display:block; } #message {display:none;}

这样,只有js可用的时候id为message的元素才会显示;如果不支持js,则该元素不会显示。

26.监听不存在的元素上的事件。

jQuery拥有一个先进的事件处理机制,通过on()方法可以监听还不存在的事件。 这是因为on方法可以传递一个元素的子元素选择器作为参数。看下面的例子:

<ul> <li>Old</li> <li>Old</li> <li>Old</li> <li>Old</li> </ul> var list = $('#testList'); // Binding an event on the list, but listening for events on the li items: list.on('click','li',function(){ $(this).remove(); }); // This allows us to create li elements at a later time, // while keeping the functionality in the event listener list.append('<li>New item (click me!)</li>');

这样,即使li是后创建的,也可以通过on()方法来监听。

27.只使用一次事件监听。

有时,我们只需要绑定只运行一次的事件处理程序。那么one()方法是一个不错的选择,通过它你就可以高枕无忧了。

<button>Press me!</ul> var press = $('#press'); // There is a method that does exactly that, the one(): press.one('click',function(){ alert('This alert will pop up only once'); }); // What this method does, is call on() behind the scenes, // with a 1 as the last argument: // press.on('click',null,null,function(){alert('I am the one and only!');}, 1); 28.模拟触发事件。

我们可以通过使用trigger模拟触发一个click事件。

<button>Press me!</ul> var press = $('#press'); // Just a regular event listener: press.on('click',function(e, how){ how = how || ''; alert('The buton was clicked ' + how + '!'); }); // Trigger the click event press.trigger('click'); // Trigger it with an argument press.trigger('click',['fast']); 29.使用触摸事件。

使用触摸事件和相关的鼠标事件并没有太多不同,但是你得有一个方便的移动设备来测试会更好。看下面这个例子。

// Define some variables var ball = $('&lt;div&gt;&lt;/div&gt;').appendTo('body'), startPosition = {}, elementPosition = {}; // Listen for mouse and touch events ball.on('mousedown touchstart',function(e){ e.preventDefault(); // Normalizing the touch event object e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; // Recording current positions startPosition = {x: e.pageX, y: e.pageY}; elementPosition = {x: ball.offset().left, y: ball.offset().top}; // These event listeners will be removed later ball.on('mousemove.rem touchmove.rem',function(e){ e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e; ball.css({ top:elementPosition.y + (e.pageY - startPosition.y), left: elementPosition.x + (e.pageX - startPosition.x), }); }); }); ball.on('mouseup touchend',function(){ // Removing the heavy *move listeners ball.off('.rem'); }); 30.更好地使用on()/off()方法。

在jQuery1.7版本时对事件处理进行了简化,看看下面的例子吧。

<div> <button>1</button> <button>2</button> <button>3</button> <button>4</button> <button>Clear</button> </div> // Lets cache some selectors var button1 = $('#button1'), button2 = $('#button2'), button3 = $('#button3'), button4 = $('#button4'), clear = $('#clear'), holder = $('#holder'); // Case 1: Direct event handling button1.on('click',function(){ log('Click'); }); // Case 2: Direct event handling of multiple events button2.on('mouseenter mouseleave',function(){ log('In/Out'); }); // Case 3: Data passing button3.on('click', Math.round(Math.random()*20), function(e){ // This will print the same number over and over again, // as the random number above is generated only once: log('Random number: ' + e.data); }); // Case 4: Events with a namespace button4.on('click.temp', function(e){ log('Temp event!'); }); button2.on('click.temp', function(e){ log('Temp event!'); }); // Case 5: Using event delegation $('#holder').on('click', '#clear', function(){ log.clear(); }); // Case 6: Passing an event map var t; // timer clear.on({ 'mousedown':function(){ t = new Date(); }, 'mouseup':function(){ if(new Date() - t &gt; 1000){ // The button has been held pressed // for more than a second. Turn off // the temp events $('button').off('.temp'); alert('The .temp events were cleared!'); } } }); 31.更快地阻止默认事件行为。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • Jquery数组操作技巧 - snowfly123

    Jquery数组操作技巧 - snowfly123

    2017-03-21 14:02

  • javascript之jQuery 性能优化技巧

    javascript之jQuery 性能优化技巧

    2017-03-19 18:05

  • JQuery实用技巧总结

    JQuery实用技巧总结

    2017-03-19 12:04

  • webjx收集45个jQuery导航插件和教程

    webjx收集45个jQuery导航插件和教程

    2017-03-18 16:00

网友点评
<