cll*_*pse 507 javascript jquery
And*_*ech 252
创建HTML元素并保留引用
var newDiv = $("<div />");
newDiv.attr("id", "myNewDiv").appendTo("body");
/* Now whenever I want to append the new div I created,
I can just reference it from the "newDiv" variable */
Run Code Online (Sandbox Code Playgroud)
检查元素是否存在
if ($("#someDiv").length)
{
// It exists...
}
Run Code Online (Sandbox Code Playgroud)
编写自己的选择器
$.extend($.expr[":"], {
over100pixels: function (e)
{
return $(e).height() > 100;
}
});
$(".box:over100pixels").click(function ()
{
alert("The element you clicked is over 100 pixels height");
});
Run Code Online (Sandbox Code Playgroud)
Nat*_*ong 95
你可以嵌套过滤器(如此处所示的nickf).
.filter(":not(:has(.selected))")
Run Code Online (Sandbox Code Playgroud)
Oli*_*Oli 80
我真的不喜欢这条$(document).ready(fn)捷径.当然它减少了代码,但它也减少了代码的可读性.当你看到$(document).ready(...),你知道你在看什么.$(...)用于太多其他方式立即有意义.
如果你有多个框架可以jQuery.noConflict();按照你的说法使用,但你也可以为它分配一个不同的变量:
var $j = jQuery.noConflict();
$j("#myDiv").hide();
Run Code Online (Sandbox Code Playgroud)
如果您有几个可以简化为$x(...)-style调用的框架,那将非常有用.
Fil*_*vić 77
哦,我们不要忘记jQuery元数据!data()函数很棒,但必须通过jQuery调用填充.
而不是违反W3C对自定义元素属性的遵从性,例如:
<input
name="email"
validation="required"
validate="email"
minLength="7"
maxLength="30"/>
Run Code Online (Sandbox Code Playgroud)
改为使用元数据:
<input
name="email"
class="validation {validate: email, minLength: 2, maxLength: 50}" />
<script>
jQuery('*[class=validation]').each(function () {
var metadata = $(this).metadata();
// etc.
});
</script>
Run Code Online (Sandbox Code Playgroud)
TM.*_*TM. 73
为与选择器匹配的任何元素设置事件处理程序,即使它在初始页面加载后被添加到DOM:
$('button.someClass').live('click', someFunction);
Run Code Online (Sandbox Code Playgroud)
这允许您通过ajax加载内容,或通过javascript添加它们,并自动为这些元素正确设置事件处理程序.
同样,要停止实时事件处理:
$('button.someClass').die('click', someFunction);
Run Code Online (Sandbox Code Playgroud)
与常规事件相比,这些实时事件处理程序有一些限制,但它们对大多数情况都很有用.
有关更多信息,请参阅jQuery文档.
更新:live()并die()在jQuery 1.7中弃用.有关类似的替换功能,请访问http://api.jquery.com/on/和http://api.jquery.com/off/.
UPDATE2:live()长期以来一直被弃用,甚至在jQuery 1.7之前.对于1.7之前的版本jQuery 1.4.2+ delegate()和使用undelegate().的live()例子($('button.someClass').live('click', someFunction);)可以使用改写delegate()这样的:$(document).delegate('button.someClass', 'click', someFunction);.
ken*_*ken 46
用命名函数替换匿名函数.这真的取代了jQuery上下文,但是由于它依赖于回调函数,它在使用jQuery时似乎更加发挥作用.我使用内联匿名函数的问题是它们更难调试(更容易查看具有明确命名函数的callstack,而不是6级"匿名"),以及同一个内部的多个匿名函数这一事实jQuery链可能变得难以阅读和/或维护.另外,匿名函数通常不会被重用; 另一方面,声明命名函数鼓励我编写更有可能被重用的代码.
插图; 代替:
$('div').toggle(
function(){
// do something
},
function(){
// do something else
}
);
Run Code Online (Sandbox Code Playgroud)
我更喜欢:
function onState(){
// do something
}
function offState(){
// do something else
}
$('div').toggle( offState, onState );
Run Code Online (Sandbox Code Playgroud)
cll*_*pse 45
在元素创建时定义属性
在jQuery 1.4中,您可以使用对象文字在创建元素时定义属性:
var e = $("<a />", { href: "#", class: "a-class another-class", title: "..." });
Run Code Online (Sandbox Code Playgroud)
...你甚至可以添加样式:
$("<a />", {
...
css: {
color: "#FF0000",
display: "block"
}
});
Run Code Online (Sandbox Code Playgroud)
nic*_*ckf 43
而不是为jQuery对象使用不同的别名(当使用noConflict时),我总是通过将其全部包装在闭包中来编写我的jQuery代码.这可以在document.ready函数中完成:
var $ = someOtherFunction(); // from a different library
jQuery(function($) {
if ($ instanceOf jQuery) {
alert("$ is the jQuery object!");
}
});
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
(function($) {
$('...').etc() // whatever jQuery code you want
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
我发现这是最便携的.我一直在研究同时使用Prototype和jQuery的网站,这些技术避免了所有冲突.
red*_*are 39
jQuery有.index但是使用起来很痛苦,因为你需要元素列表,并传入你想要索引的元素:
var index = e.g $('#ul>li').index( liDomObject );
Run Code Online (Sandbox Code Playgroud)
以下更容易:
如果您想知道无序列表中集合中元素的索引(例如列表项):
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
Run Code Online (Sandbox Code Playgroud)
cll*_*pse 23
准备活动的简写
明确而冗长的方式:
$(document).ready(function ()
{
// ...
});
Run Code Online (Sandbox Code Playgroud)
简写:
$(function ()
{
// ...
});
Run Code Online (Sandbox Code Playgroud)
msh*_*rir 22
在核心jQuery函数上,除了selector参数之外还指定context参数.指定context参数允许jQuery从DOM中的更深层分支开始,而不是从DOM根开始.给定足够大的DOM,指定上下文参数应转换为性能增益.
示例:在文档的第一个表单中查找无线电类型的所有输入.
$("input:radio", document.forms[0]);
Run Code Online (Sandbox Code Playgroud)
参考:http://docs.jquery.com/Core/jQuery#expressioncontext
Aar*_*ell 21
不仅仅是jQuery,但我为jQuery和MS AJAX做了一个很好的小桥:
Sys.UI.Control.prototype.j = function Sys$UI$Control$j(){
return $('#' + this.get_id());
}
Run Code Online (Sandbox Code Playgroud)
如果你正在做很多ASP.NET AJAX,这真的很好,因为MS支持jQuery现在有一个很好的桥接意味着它很容易做jQuery操作:
$get('#myControl').j().hide();
Run Code Online (Sandbox Code Playgroud)
所以上面的例子不是很好,但是如果你正在编写ASP.NET AJAX服务器控件,那么就可以轻松地在客户端控件实现中使用jQuery.
cll*_*pse 20
优化复杂选择器的性能
使用复杂选择器时,查询DOM的子集可以显着提高性能:
var subset = $("");
$("input[value^='']", subset);
Run Code Online (Sandbox Code Playgroud)
egy*_*ado 19
说到提示和技巧以及一些教程.我发现这些教程系列("jQuery的绝对初学者"视频系列)由杰弗里方式是非常有帮助的.
它针对那些不熟悉jQuery的开发人员.他展示了如何使用jQuery创建许多很酷的东西,比如动画,创建和删除元素等......
我从中学到了很多东西.他展示了如何使用jQuery很容易.现在我喜欢它,我可以阅读和理解任何jQuery脚本,即使它很复杂.
这是一个我喜欢" 调整文本大小 "的例子
1- jQuery ......
<script language="javascript" type="text/javascript">
$(function() {
$('a').click(function() {
var originalSize = $('p').css('font-size'); // get the font size
var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable "originalSize"
var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch
$('p').css('font-size', number / 1.2 + unitOfMeasure);
if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
2- CSS造型......
<style type="text/css" >
body{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}
.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}
</style>
Run Code Online (Sandbox Code Playgroud)
2- HTML ...
<div class="box">
<a href="#" id="larger">Larger</a> |
<a href="#" id="Smaller">Smaller</a>
<p>
In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods.
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
强烈推荐这些教程......
http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/
One*_*erd 19
异步each()函数
如果你有非常复杂的文件运行jquery 每个()函数在迭代期间锁定浏览器,和/或Internet Explorer弹出" 你想继续运行这个脚本 "的消息,这个解决方案将节省一天.
jQuery.forEach = function (in_array, in_pause_ms, in_callback)
{
if (!in_array.length) return; // make sure array was sent
var i = 0; // starting index
bgEach(); // call the function
function bgEach()
{
if (in_callback.call(in_array[i], i, in_array[i]) !== false)
{
i++; // move to next item
if (i < in_array.length) setTimeout(bgEach, in_pause_ms);
}
}
return in_array; // returns array
};
jQuery.fn.forEach = function (in_callback, in_optional_pause_ms)
{
if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default
return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it
};
Run Code Online (Sandbox Code Playgroud)
你可以使用它的第一种方式就像每个():
$('your_selector').forEach( function() {} );
Run Code Online (Sandbox Code Playgroud)
一个可选的第二参数,可以指定在迭代之间的速度/延迟其可以是用于动画有用(在下面的例子将在等待1秒迭代之间):
$('your_selector').forEach( function() {}, 1000 );
Run Code Online (Sandbox Code Playgroud)
请记住,由于这是异步工作,因此您不能依赖迭代在下一行代码之前完成,例如:
$('your_selector').forEach( function() {}, 500 );
// next lines of code will run before above code is complete
Run Code Online (Sandbox Code Playgroud)
我为一个内部项目编写了这个,虽然我确信它可以改进,但它适用于我们需要的东西,所以希望你们中的一些人觉得它很有用.谢谢 -
cll*_*pse 18
Syntactic shorthand-sugar-thing - 在一行上缓存对象集合并执行命令:
代替:
var jQueryCollection = $("");
jQueryCollection.command().command();
Run Code Online (Sandbox Code Playgroud)
我做:
var jQueryCollection = $("").command().command();
Run Code Online (Sandbox Code Playgroud)
一个有点"真实"的用例可能是这样的:
var cache = $("#container div.usehovereffect").mouseover(function ()
{
cache.removeClass("hover").filter(this).addClass("hover");
});
Run Code Online (Sandbox Code Playgroud)
Ben*_*use 15
我喜欢$this在匿名函数的开头声明一个变量,所以我知道我可以引用一个jQueried.
像这样:
$('a').each(function() {
var $this = $(this);
// Other code
});
Run Code Online (Sandbox Code Playgroud)
Nat*_*ong 14
将jQuery对象保存到变量可让您重用它,而无需通过搜索DOM来查找它.
(正如@Louis建议的那样,我现在使用$来表示变量包含一个jQuery对象.)
// Bad: searching the DOM multiple times for the same elements
$('div.foo').each...
$('div.foo').each...
// Better: saving that search for re-use
var $foos = $('div.foo');
$foos.each...
$foos.each...
Run Code Online (Sandbox Code Playgroud)
作为一个更复杂的例子,假设您在商店中有食物清单,并且您只想显示符合用户标准的食物.您有一个带有复选框的表单,每个复选框都包含一个条件.复选框的名称organic和lowfat,并且产品具有相应的类 - .organic等.
var $allFoods, $matchingFoods;
$allFoods = $('div.food');
Run Code Online (Sandbox Code Playgroud)
现在您可以继续使用该jQuery对象了.每次单击一个复选框(检查或取消选中),从主食品列表开始,并根据复选框过滤:
// Whenever a checkbox in the form is clicked (to check or uncheck)...
$someForm.find('input:checkbox').click(function(){
// Start out assuming all foods should be showing
// (in case a checkbox was just unchecked)
var $matchingFoods = $allFoods;
// Go through all the checked boxes and keep only the foods with
// a matching class
this.closest('form').find("input:checked").each(function() {
$matchingFoods = $matchingFoods.filter("." + $(this).attr("name"));
});
// Hide any foods that don't match the criteria
$allFoods.not($matchingFoods).hide();
});
Run Code Online (Sandbox Code Playgroud)
Jan*_*ich 11
似乎已经提到了大多数有趣且重要的提示,所以这只是一点补充.
小技巧是jQuery.each(对象,回调)函数.每个人都可能使用jQuery.each(回调)函数迭代jQuery对象本身,因为它很自然.jQuery.each(对象,回调)实用程序函数迭代对象和数组.很长一段时间,我不知道除了不同的语法之外没有看到它是什么(我不介意编写所有时尚的循环),而且我有点惭愧,我最近才意识到它的主要优势.
问题在于,由于jQuery.each(对象,回调)中的循环体是一个函数,因此每次在循环中都会得到一个新的作用域,这在循环中创建闭包时特别方便.
换句话说,一个典型的常见错误是执行以下操作:
var functions = [];
var someArray = [1, 2, 3];
for (var i = 0; i < someArray.length; i++) {
functions.push(function() { alert(someArray[i]) });
}
Run Code Online (Sandbox Code Playgroud)
现在,当您调用functions数组中的函数时,您将获得三次警报,其内容undefined很可能不是您想要的.问题是只有一个变量i,所有三个闭包都引用它.当循环结束时,最终值为i3,并且someArrary[3]是undefined.您可以通过调用另一个为您创建闭包的函数来解决它.或者您使用jQuery实用程序,它基本上会为您执行此操作:
var functions = [];
var someArray = [1, 2, 3];
$.each(someArray, function(item) {
functions.push(function() { alert(item) });
});
Run Code Online (Sandbox Code Playgroud)
现在,当您调用这些函数时,您将获得三个警报,其中包含内容1,2和3.
一般来说,这是你自己无法做到的事情,但它很高兴.
cll*_*pse 11
像访问数组一样访问jQuery函数
基于布尔值添加/删除类...
function changeState(b)
{
$("selector")[b ? "addClass" : "removeClass"]("name of the class");
}
Run Code Online (Sandbox Code Playgroud)
是...的缩短版本
function changeState(b)
{
if (b)
{
$("selector").addClass("name of the class");
}
else
{
$("selector").removeClass("name of the class");
}
}
Run Code Online (Sandbox Code Playgroud)
没有那么多的用例.从来没有; 我觉得它很整洁:)
更新
如果你不是注释读取类型,ThiefMaster指出toggleClass接受一个布尔值,它确定是否应该添加或删除一个类.因此,就我上面的示例代码而言,这将是最好的方法......
$('selector').toggleClass('name_of_the_class', true/false);
Run Code Online (Sandbox Code Playgroud)
从集合中删除元素并保留可链接性
考虑以下:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
$("li").filter(function()
{
var text = $(this).text();
// return true: keep current element in the collection
if (text === "One" || text === "Two") return true;
// return false: remove current element from the collection
return false;
}).each(function ()
{
// this will alert: "One" and "Two"
alert($(this).text());
});
Run Code Online (Sandbox Code Playgroud)
该filter()函数从jQuery对象中删除元素.在这种情况下:将删除所有不包含文本"One"或"Two"的li元素.
更新:
只需在网站上包含此脚本,您就可以在任何浏览器中弹出一个Firebug控制台进行调试.不完整的功能,但它仍然非常有用!记得在完成后将其删除.
<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
Run Code Online (Sandbox Code Playgroud)
看看这个链接:
更新:我找到了新的东西; 它是JQuery Hotbox.
Google在Google Code上托管了多个JavaScript库.从那里加载它可以节省带宽,并加载已经缓存的快速cos.
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load jQuery
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
// Your code goes here.
});
</script>
Run Code Online (Sandbox Code Playgroud)
要么
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
您还可以使用它来判断图像何时完全加载.
$('#myImage').attr('src', 'image.jpg').load(function() {
alert('Image Loaded');
});
Run Code Online (Sandbox Code Playgroud)
firebug的"console.info",您可以使用它将消息和变量转储到屏幕而不必使用警告框."console.time"允许您轻松设置一个计时器来包装一堆代码并查看它需要多长时间.
console.time('create list');
for (i = 0; i < 1000; i++) {
var myList = $('.myList');
myList.append('This is list item ' + i);
}
console.timeEnd('create list');
Run Code Online (Sandbox Code Playgroud)
小智 9
在可能的情况下使用伪选择器的过滤方法,以便jQuery可以使用querySelectorAll(这比sizzle快得多).考虑这个选择器:
$('.class:first')
Run Code Online (Sandbox Code Playgroud)
可以使用以下方法进行相同的选择:
$('.class').eq(0)
Run Code Online (Sandbox Code Playgroud)
哪个必须更快,因为'.class'的初始选择是QSA兼容的
更改输入元素的类型
当我试图改变已经附加到DOM的输入元素的类型时,我遇到了这个问题.您必须克隆现有元素,将其插入旧元素之前,然后删除旧元素.否则它不起作用:
var oldButton = jQuery("#Submit");
var newButton = oldButton.clone();
newButton.attr("type", "button");
newButton.attr("id", "newSubmit");
newButton.insertBefore(oldButton);
oldButton.remove();
newButton.attr("id", "Submit");
Run Code Online (Sandbox Code Playgroud)
换行符和可链接性
在链接上链接多个调用时......
$("a").hide().addClass().fadeIn().hide();
Run Code Online (Sandbox Code Playgroud)
您可以使用换行符提高可读性.像这样:
$("a")
.hide()
.addClass()
.fadeIn()
.hide();
Run Code Online (Sandbox Code Playgroud)
触发动画时使用.stop(true,true)可防止重复动画.这对于翻转动画特别有用.
$("#someElement").hover(function(){
$("div.desc", this).stop(true,true).fadeIn();
},function(){
$("div.desc", this).fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
在方法调用中使用自执行匿名函数,例如.append()迭代某些东西.IE:
$("<ul>").append((function ()
{
var data = ["0", "1", "2", "3", "4", "5", "6"],
output = $("<div>"),
x = -1,
y = data.length;
while (++x < y) output.append("<li>" + info[x] + "</li>");
return output.children();
}()));
Run Code Online (Sandbox Code Playgroud)
我用这个来迭代那些大而不舒服的东西,以打破我的链接构建.
这个去了Kobi.
请考虑以下代码段:
// hide all elements which contains the text "abc"
$("p").each(function ()
{
var that = $(this);
if (that.text().indexOf("abc") > -1) that.hide();
});
Run Code Online (Sandbox Code Playgroud)
这是一个速记......大约快两倍:
$("p.value:contains('abc')").hide();
Run Code Online (Sandbox Code Playgroud)
类固醇支持HTML5数据属性!
该数据功能之前已经提及.有了它,您就可以将数据与DOM元素相关联.
最近,jQuery团队增加了对HTML5自定义data-*属性的支持.好像这还不够; 他们用类固醇强制数据函数,这意味着你可以直接在你的标记中以JSON的形式存储复杂的对象.
HTML:
<p data-xyz = '{"str": "hi there", "int": 2, "obj": { "arr": [1, 2, 3] } }' />
Run Code Online (Sandbox Code Playgroud)
JavaScript:
var data = $("p").data("xyz");
data.str // "hi there"
typeof data.str // "string"
data.int + 2 // 4
typeof data.int // "number"
data.obj.arr.join(" + ") + " = 6" // "1 + 2 + 3 = 6"
typeof data.obj.arr // "object" ... Gobbles! Errrghh!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60588 次 |
| 最近记录: |