jQuery Tips
jQuery Tips Summary
- Using multiple selector
- Add check to checkbox
- Check whether the checkbox is checked or not
- How to make a lot of table row
- Display Size
- Save data in DOM
- Optimization
Using multiple selector
OR
selector1 or selctor2
var el = $(".a", "#test");
AND
selector1 and selector2
var el = $(".b" + "#test");
Add check to checkbox
$("#element").attr('checked', true);
If you want to remove check, use removeAttr
$("#element").removeAttr('checked');
Check whether the checkbox is checked or not
var checked = $('#element').is(':checked');
checked is true or false(boolean)
How to make a lot of table row
To use clone technique.
Prepare tr element as with hidden attr(hidden(display:none)). This is row template.
var tr = $(element).clone(); $(table).append(tr);
Display Size
window object
winHeight = $(window).height(); winWidth = $(window).width();
Save data in DOM
Setter
$("").data("key", data);
data is javascript object. Any type is fine.
Getter
$("").data("key");
This data is combined with DOM
Optimization
Use id
id is faster than other selectors.
$("#xxx");
Use class name ant element name together.
This is faster than single class name use.
$("div.clazz1");
Simple is best!
$("#nav a"); // Fast $("#nav ul li a"); // A bit slow
Find
$("#nav").find("a"); // Fast $("#nav a"); // A bit slow
Cache jQuery object using var if use multiple
var element = $("#id");
Reduce DOM operations
var ul = $("ul"); var lis; for ( var i=0;i < 50;i++ ) { lis += '<li>' + i + '<li>'; } ul.append(lis);