2013年10月17日 星期四

(js常見問題)javascript、jQuery 特定解法和函數

http://www.codebit.cn/javascript/javascript-replace.html
String.replace( ) 将所有字符首字母大写

var text = 'a journey of a thousand miles begins with single step.';
text.replace(/\b\w+\b/g, function(word) {
                           return word.substring(0,1).toUpperCase( ) +
                                  word.substring(1);
                         });
 
// 返回:A Journey Of A Thousand Miles Begins With Single Step.


http://stackoverflow.com/questions/8743026/how-to-use-in-jquery-not-and-hasclass-to-get-a-specific-element-without-a-cla
判斷某個dom有沒有該class名字
if(!$('#foo').hasClass('bar')) return;
..// do something if DOM has 'bar' className

http://www.w3school.com.cn/jquery/event_target.asp
e.target =>target 属性规定哪个 DOM 元素触发了该事件。

Cancelling previous ajax request jquery => 只顯示最後一次傳回來的內容
http://stackoverflow.com/questions/4342438/cancelling-previous-ajax-request-jquery/4342484#4342484
  
var fooXHR, fooCounter=0;
$(...).bind( 'someEvent', function(){
  // Do the Right Thing to indicate that we don't care about the request anymore
  if (fooXHR) fooXHR.abort();

  var token = ++fooCounter;
  fooXHR = $.get( ..., function(data){
    // Even aborted XHR may cause the callback to be invoked
    if (token != fooCounter) return;

    // At this point we know that we're using the data from the latest request
  });
});
  


查某個元素是否有顯示
http://stackoverflow.com/questions/8337186/jquery-isvisible-not-working-in-chrome/17489974#17489974
$("#makespan").is(":visible")

Remove all classes that begin with a certain string =>因addClass和removeClass一次會新增或刪除一個class的名字,要一次全刪除用下面這句
http://stackoverflow.com/questions/57812/remove-all-classes-that-begin-with-a-certain-string
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');

Detecting arrow key presses in JavaScript
http://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript
arrow keys are only triggered by onkeydown, not onkeypress
keycodes are:
  • left = 37
  • up = 38
  • right = 39
  • down = 40

Change by jquery css bottom & top more once
http://stackoverflow.com/questions/6498290/change-by-jquery-css-bottom-top-more-once
{ bottom: 250, top: 'auto' }
{ top: 100, bottom: 'auto' }

jQuery get mouse position within an element
http://stackoverflow.com/questions/4249648/jquery-get-mouse-position-within-an-element

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});



prototype.js的ajax同步處理
http://www.wrox.com/WileyCDA/Section/Ajax-in-Prototype.id-306214.html

var oOptions = {
    method: "get",
    parameters: "name=Nicholas",
    asynchronous: false  //asynchronous =>非同步
};


http://api.jquery.com/load/
使用.load() 讓圖片完全載入後再執行callback的js

jQuery 的 live() 被 Deprecate 了
http://blog.timc.idv.tw/posts/deprecation-of-jquery-live-function/

// 舊
$('#myid').bind(event, fn);
// 新 (改名字就好)
$('#myid').on(event, fn);

// 舊
$('#not_in_dom_yet').live(event, fn)
// 新
$(document).on(event, '#not_in_dom_yet', fn);



JavaScript sort() 方法
http://www.w3school.com.cn/js/jsref_sort.asp
function sortNumber(a,b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

document.write(arr + "
")
document.write(arr.sort(sortNumber))



输出:
10,5,40,25,1000,1
1,5,10,25,40,1000


Firefox的'too much recursion' jQuery錯誤:(這邊非唯一解,只適用我這邊的狀況)
<div class="filter_box">
    <img src="xxx.jpg">
</div>

$('div.filter_box').live('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    $(this).children(":first").trigger('click');
});

將live改成on即解決,(儘量少用live)

傳參數到jQuery的trigger裡面
http://stackoverflow.com/questions/16401538/passing-parameters-on-jquery-trigger

$('body').trigger('this_works', [{data: [1, 2, 3]}, 'something']);

$('body').on('this_works', function (event, json, string) {
  controller.listen(event, json, string);
});

jQuery.extend的用法
http://blog.darkthread.net/post-2009-03-01-jquery-extend.aspx
以jQuery.extend(objA, objB)為例,你可以想像成objA與objB各有一些屬性(方法也會比照處理,在此只提屬性),extend()會將objB有而objA沒有的屬性加到objA裡,如果objB裡的某個屬性,objA裡剛好也有同名的屬性,則會用objB的屬性值去覆寫objA原有的屬性。

找父元素最近有該class的元素
http://stackoverflow.com/questions/5333426/how-to-find-a-parent-with-a-known-class-in-jquery
$(this).closest('.class_name');

使用jquery複製div到另一個div
http://stackoverflow.com/questions/16068047/jquery-duplicate-div-into-another-div
$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

使用多種條件切開字串
http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
>> "Hello awesome, world!".split(/[\s,]+/)   //遇到逗號(,)或空白就切開字串

只移除($.off)特定的事件
http://api.jquery.com/off/
Example: Unbind all delegated event handlers by their namespace:
var validate = function() {
  // Code to validate form entries
};
 
// Delegate events under the ".validator" namespace
$( "form" ).on( "click.validator", "button", validate );
 
$( "form" ).on( "keypress.validator", "input[type='text']", validate );
 
// Remove event handlers in the ".validator" namespace
$( "form" ).off( ".validator" );



刪除節點後面的字
http://stackoverflow.com/questions/6690445/how-to-remove-text-inside-an-element-with-jquery
HTML:
<li>
    <div>Some stuff</div>
    <a href="http://www.mysite.com/">New Item</a>
    (1 vote)
</li>
(要移除 (1 vote) )
This should work.

$("li").contents().filter(function(){ return this.nodeType != 1; }).remove();
or by specifying text nodes explicitly

$("li").contents().filter(function(){ return this.nodeType == 3; }).remove();
要加回字,用after:
$("li a").after("add text");

混合多個節點到jQuery 物件
http://stackoverflow.com/questions/1881716/merging-jquery-objects
使用 $.add

在前端排序資料套件( jQuery datatables )
http://datatables.net/download/
錯誤: TypeError: oColumn is undefined
http://stackoverflow.com/questions/12280900/typeerror-ocolumn-is-undefined-when-using-jquery-datatables-library
解法: table裡面必須使用 <thead> 和 <tbody> 標籤
錯誤: TypeError: nCell is undefined
http://stackoverflow.com/questions/12472726/datatables-ncell-is-undefined-error-with-valid-xhtml
解法: th和td的數量必須相等
修改分頁數量(預設為5)
http://stackoverflow.com/questions/12684328/rails-bootstrap-datatables
$.fn.dataTableExt.oPagination.iFullNumbersShowPages = 10;

移除特定class
http://stackoverflow.com/questions/15618005/jquery-regexp-selecting-and-removeclass
$("#foo").removeClass( function() { /* Matches even table-col-row */
     var toReturn = '',
         classes = this.className.split(' ');
     for(var i = 0; i < classes.length; i++ ) {
         if( /(Nice|Naughty|你要的class名字)/.test( classes[i] ) ) { /* Filters */
             toReturn += classes[i] +' ';
         }
     }
     return toReturn ; /* Returns all classes to be removed */
});

比較兩個object是否為同一個DOM
http://help.dottoro.com/ljlpvjmd.php
使用 isEqualNode ( IE9以上才支援, opera不支援)

小數點後二位四捨五入
http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript?page=1&tab=votes#tab-top
Math.round(num * 100) / 100

物件轉字串
http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string
var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

javascript 的if中有逗號(commas)
以最後一組傳回值為結果
Ex.
!!(a=2, b=3, a==b, a!==b)  // true

在submit時新增參數(非ajax)
http://stackoverflow.com/questions/2530635/jquery-add-additional-parameters-on-submit-not-ajax
var input = $("<input>").attr("type", "hidden").attr("name", "think_action").val(action);
$('#import_form').append($(input));

上傳檔案按鈕不使用file input原本樣式
http://stackoverflow.com/questions/8350927/file-upload-button-without-input-field
解法:把原本input file隱藏,然後再畫一個新按鈕去觸發事件
HTML:
<input type="file" name="somename" size="chars">
<button>Choose File</button>
CSS:
input[type='file'] {
    display: none;
}
JS:
$('button').click(function(){
    $('input').click();
});

讓第二個table寬度與第一個table前幾個寬度一樣
http://stackoverflow.com/questions/1865552/selecting-the-first-n-items-with-jquery  Selecting the first “n” items with jQuery
http://stackoverflow.com/questions/1015669/calculate-total-width-of-children-with-jquery  Calculate total width of Children with jQuery
http://stackoverflow.com/questions/349705/total-width-of-element-including-padding-and-border-in-jquery  Total width of element (including padding and border) in jQuery
Ex.
code:
var width = 0;
$(".table1 th").slice(0,4).each(function() {
 width += $(this).outerWidth();
});
$('.table2').css('width', width);
說明:
使用 $(".table1 th").slice(0,4) 抓前四個元素,再用each跑迴圈,最後用$(this).outerWidth() 獲取每個th的寬度並加總
$(elem).outerWidth(); // Returns the width + padding + borders
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins

jQuery 正規式選擇器
http://stackoverflow.com/questions/3568200/regular-expressions-in-a-jquery-selector
$('input').filter(function () { return /^[a-z]+_[1-9].*/.test(this.name); })

查該元素是父元素下的第幾個元素
http://stackoverflow.com/questions/3159372/how-determine-child-ordinal-position-need-parent-ordinalchildsome-chi
$('#parent').children().index('#some-child');

jQuery移除HTML字串中某個TAG
http://stackoverflow.com/questions/12109946/jquery-remove-tag-from-html-string
var removeElements = function(text, selector) {
    var wrapped = $("<div>" + text + "</div>");
    wrapped.find(selector).remove();
    return wrapped.html();
}
USAGE:
var removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");
// removedSpanString  = " Some other Text"







沒有留言:

張貼留言