21. 如何替换串中的词
- var el = $('#id');
- el.html(el.html().replace(/word/ig, ''));
22. 如何禁用右键单击上下文菜单:
- $(document).bind('contextmenu',function(e){
- return false;
- });
23. 如何定义一个定制的选择器
广州网站建设,网站建设,广州网页设计,广州网站设计
- $.expr[':'].mycustomselector = function(element, index, meta, stack){
- // element- 一个DOM元素
- // index – 栈中的当前循环索引
- // meta – 有关选择器的元数据
- // stack – 要循环的所有元素的栈
- // 如果包含了当前元素就返回true
- // 如果不包含当前元素就返回false };
- // 定制选择器的用法:
- $('.someClasses:test').doSomething();
24. 如何检查某个元素是否存在
- if ($('#someDiv').length) {
- //万岁!!!它存在……
- }
25. 如何使用jQuery来检测右键和左键的鼠标单击两种情况:
- $("#someelement").live('click', function(e) {
- if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
- alert("Left Mouse Button Clicked");
- } else if(e.button == 2) {
- alert("Right Mouse Button Clicked");
- }
- });
26. 如何显示或是删除input域中的默认值
- //这段代码展示了在用户未输入值时,
- //如何在文本类型的input域中保留
- //一个默认值
- wap_val = [];
- $(".swap").each(function(i){
- wap_val[i] = $(this).val();
- $(this).focusin(function(){
- if ($(this).val() == swap_val[i]) {
- $(this).val("");
- }
- }).focusout(function(){
- if ($.trim($(this).val()) == "") {
- $(this).val(swap_val[i]);
- }
- });
- });
27. 如何在一段时间之后自动隐藏或关闭元素(支持1.4版本):
- //这是1.3.2中我们使用setTimeout来实现的方式
- setTimeout(function() {
- $('.mydiv').hide('blind', {}, 500)
- }, 5000);
- //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠)
- $(".mydiv").delay(5000).hide('blind', {}, 500);
28. 如何把已创建的元素动态地添加到DOM中:
广州网站建设,网站建设,广州网页设计,广州网站设计
- var newDiv = $('');
- newDiv.attr('id','myNewDiv').appendTo('body');
29. 如何限制“Text-Area”域中的字符的个数:
- jQuery.fn.maxLength = function(max){
- this.each(function(){
- var type = this.tagName.toLowerCase();
- var inputType = this.type? this.type.toLowerCase() : null;
- if(type == "input" && inputType == "text" || inputType == "password"){
- //Apply the standard maxLength
- this.maxLength = max;
- }
- else if(type == "textarea"){
- this.onkeypress = function(e){
- var ob = e || event;
- var keyCode = ob.keyCode;
- var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
- return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
- };
- this.onkeyup = function(){
- if(this.value.length > max){
- this.value = this.value.substring(0,max);
- }
- };
- }
- });
- };
- //用法
- $('#mytextarea').maxLength(500);
30. 如何为函数创建一个基本的测试
- //把测试单独放在模块中
- module("Module B");
- test("some other test", function() {
- //指明测试内部预期有多少要运行的断言
- expect(2);
- //一个比较断言,相当于JUnit的assertEquals
- equals( true, false, "failing test" );
- equals( true, true, "passing test" );
- });