1.jQuery(expression, [context])默认情况下, 如果没有指定context参数,$()将在当前的 HTML document中查找 DOM 元素;如果指定了 context 参数,如一个 DOM 元素集或 jQuery 对象,那就会在这个 context 中查找。
例如:
获取父窗口的元素方法:$(selector, window.parent.document);
在文档的第一个表单中,查找所有的单选按钮(即: type 值为 radio 的 input 元素):$("input:radio", document.forms[0]);
2. 编写一个简单的 jQuery 插件(模板)
//You need an anonymous function to wrap around your function to avoid conflict
(function($){
//method一:
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
pluginname: function() {
//options
// var defaults = {
// option1: "default_value"
// }
// var options = $.extend(defaults, options);
//a public method
// this.methodName: function () {
//call this method via $.pluginname().methodName();
// }
//Iterate over the current set of matched elements
return this.each(function() {
// var o = options;
//code to be inserted here
});
}
});
//pass jQuery to the function,
//So that we will able to use any valid Javascript variable name
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )
//method二:
$.fn.pluginname=function(){
return this.each(function() { });
}
})(jQuery);
实例:
<script type="text/javascript">
(function($){
$.fn.extend({
check: function() {
return this.each(function() { alert(0); });
},
uncheck: function() {
return this.each(function() { alert(1); });
}
});
$.fn.suggest=function(){
return this.each(function() { alert(2); });
}
})(jQuery);
function check(){
if($("input").attr("checked")){
$("input").check();
}else{
$("input").uncheck();
}
$("input").suggest();
}
</script>