web前端开发JQuery常用实例代码片段(50个)

2020-05-29 07:12:58易采站长站整理

arrInputValues.push($(this ).val());
});

35. 如何从元素中除去HTML


(function ($) { $.fn.stripHtml = function () { var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function () { $(this).html($(this).html().replace(regexp, "")); }); return $(this); } })(jQuery);
//用法: $(‘p').stripHtml();

36. 如何使用closest来取得父元素


$(‘#searchBox').closest(‘div');

37. 如何使用Firebug和Firefox来记录jQuery事件日志


// 允许链式日志记录 // 用法:$('#someDiv').hide().log('div hidden').addClass('someClass'); jQuery.log = jQuery.fn.log = function (msg) { if (console) { console.log("%s: %o", msg, this); } return this; };

38. 如何强制在弹出窗口中打开链接


jQuery('a.popup').live('click', function () { newwindow = window.open($(this).attr('href'), '', 'height=200,width=150'); if (window.focus) { newwindow.focus(); } return false; });

39. 如何强制在新的选项卡中打开链接


jQuery('a.newTab').live('click', function () { newwindow = window.open($(this).href); jQuery(this).target = "_blank"; return false; });

40. 在jQuery中如何使用.siblings()来选择同辈元素


// 不这样做
$('#nav li').click(function () { $('#nav li').removeClass('active'); $(this).addClass('active'); });
//替代做法是
$('#nav li').click(function () { $(this).addClass('active').siblings().removeClass('active'); })

41. 如何切换页面上的所有复选框


var tog = false ;
// 或者为true,如果它们在加载时为被选中状态的话
$('a').click(function () { $("input[type=checkbox]").attr("checked", !tog); tog = !tog; });

42. 如何基于一些输入文本来过滤一个元素列表


//如果元素的值和输入的文本相匹配的话 //该元素将被返回
$('.someClass').filter(function () { return $(this).attr('value') == $('input#someId').val(); })

43. 如何获得鼠标垫光标位置x和y


$(document).ready(function () { $(document).mousemove(function (e) { $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); }); });

44. 如何把整个的列表元素(List Element,LI)变成可点击的 


$("ul li").click(function () { window.location = $(this).find("a").attr("href"); return false; });