> For the complete documentation index, see [llms.txt](https://stb11816.gitbook.io/python_note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stb11816.gitbook.io/python_note/web-framework/jquery.md).

# jQuery

## ajax

```javascript
// 範例
$.ajax({
  url: "url",
  async: false,
  data:{
    pid : 123,
    action: "456"
  },
  dataType: 'json',
  success: function(data) {
    console.log(data)
  },
  error: function(error){
    console.log(error)
  }
});
```

常見參數：\
type = 請求方式，預設get\
async = true or false，預設為true，所有請求均為非同步請求。改為false則同步請求將鎖住瀏覽器，使用者其它操作必須等待請求完成才可以執行。\
contentType = 傳送資訊至伺服器時內容編碼型別。預設：application/x-www-form-urlencoded\
data = 發送到伺服器的資料。將自動轉換為請求字串格式。\
dataType = 預期伺服器返回的資料型別。

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/272853/](https://codertw.com/前端開發/272853/)

<https://blog.reh.tw/archives/662>

介紹

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/272853/](https://codertw.com/前端開發/272853/)

success and error

<http://www.pureexample.com/tw/jquery/ajax-success-and-error.html>

另一種post寫法 (尚未與ajax比較)

```javascript
$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});
```

<https://stackoverflow.com/questions/18697034/how-to-pass-parameters-in-ajax-post/35590754>

傳送json資料 (400)

<https://stackoverflow.com/questions/21738663/getting-json-in-flask-from-jquery-ajax>

用enter送出

<https://www.formget.com/submit-your-form-on-pressing-enter-key-using-jquery/>

<https://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery>

## json物件處理

使用ajax post時可用JSON.stringify()轉換型態後再傳送

使用ajax get接收回傳結果時可用JSON.parse()轉換型態

```javascript
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');


var obj = { 'name': "John", "age": 30, "city": "New York" };
var myJSON = JSON.stringify(obj);


for (key in obj ){
    alert(obj[key]);
}
```

<https://www.w3schools.com/js/js_json_parse.asp>

遍歷方法

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/258763/](https://codertw.com/前端開發/258763/)

<https://t.codebug.vip/questions-342113.htm>

替換特殊字元(換行、雙引號)

<https://stackoverflow.com/questions/4253367/how-to-escape-a-json-string-containing-newline-characters-using-javascript>

日期選擇器

<http://www.daterangepicker.com/>

<https://www.wfublog.com/2017/08/jquery-date-range-picker-bootstrap.html>

<https://dotblogs.com.tw/shadow/2017/11/28/001719>

取得check box值

<http://blog.twbryce.com/jquery-get-checkbox-value/>

常用語法

```javascript
// array to string
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c


// join
array.join("+++")

// 判斷長度
if (array.length == 0){
    console.log(array.length)
}

// 取得check box值，name記得要改
var cbxVehicle = new Array();
$('input:checkbox:checked[name="vehicle"]').each(function(i) { cbxVehicle[i] = this.value; });

// 取得json的key & value
var z = {"123":"/user/home", "456":"test"} 
for (var key in z) {
        console.log(key);     //获取key值
        console.log(z[key]); //获取对应的value值
    }

// 判斷key是否存在
if (json_object.hasOwnProperty('name')) {
    //do struff
}

// 替換特殊字元後在parse  斜線的斜線數量有差
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
                                      .replace(/\\'/g, "\\'")
                                      .replace(/\\"/g, '\\"')
                                      .replace(/\\&/g, "\\&")
                                      .replace(/\\r/g, "\\r")
                                      .replace(/\\t/g, "\\t")
                                      .replace(/\\b/g, "\\b")
                                      .replace(/\\f/g, "\\f");

// 判斷是否為空字典
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false
```

checkbox 全選

<http://dev.sopili.net/2013/03/bootstrap-css.html>

cdn介紹

[https://blog.csdn.net/zyz1985/article/details/6828790](http://newaurora.pixnet.net/blog/post/128995999-cdn)

[https://hkitblog.com/%E4%B8%8D%E5%8F%AF%E4%B8%8D%E7%9F%A5%E7%9A%84-cdn-%E7%A8%AE%E9%A1%9E%EF%BC%81%E7%94%9A%E9%BA%BC%E6%98%AF%E5%8B%95%E6%85%8B%E3%80%81%E9%9D%9C%E6%85%8B-cdn%EF%BC%9Fevent-driven-%E7%AE%97%E6%98%AF/](https://hkitblog.com/不可不知的-cdn-種類！甚麼是動態、靜態-cdn？event-driven-算是/)

## string 格式化

```javascript
String.format = function() {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for ( var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};
// var a = "我喜欢吃{0}，也喜欢吃{1}，但是最喜欢的还是{0},偶尔再买点{2}";
// alert(String.format(a, "苹果","香蕉","香梨"));
// 结果:我喜欢吃苹果，也喜欢吃香蕉，但是最喜欢的还是苹果,偶尔再买点香梨
```

<https://www.cnblogs.com/taoweiji/p/3260883.html>

## radio

```javascript
// 隨著radio變更html
$('#my_radio_box').change(function() {
    var checked_id = $('input[type=radio][name=inlineDefaultRadiosExample]:checked').attr('id')  // 選中的radio值
    var selected_value = $("input[name='inlineDefaultRadiosExample']:checked").val();  // 選中的radio值

    $("#predict_result").html(crf_data[checked_id]['html']);
});
```

<https://blog.csdn.net/enjoyo/article/details/1700228>

[https://blog.xuite.net/vv650812/twblog/229550316-jQuery+%E4%B9%8B+checkbox+%E5%8F%8A+radio+%E5%8F%96%E5%80%BC%E5%8F%8A%E8%A8%AD%E5%AE%9A%E5%80%BC%E7%9A%84%E6%AD%A3%E7%A2%BA%E6%96%B9%E6%B3%95](https://blog.xuite.net/vv650812/twblog/229550316-jQuery+之+checkbox+及+radio+取值及設定值的正確方法)

## select

```javascript
<select id="sfs" name="sfsname">
  <option value="1">第一項</option>
  <option value="2">第二項</option>
  <option value="3">第三項</option>
</select>
```

取值

```javascript
 var s= $("#sfs").val();
```

<http://n.sfs.tw/content/index/10047>

## onload vs ready

ready，表示文件結構已經載入完成（不包含圖片等非文字媒體檔案）

onload，指示頁 麵包含圖片等檔案在內的所有元素都載入完成。

ready 在onload 前載入！！！

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/290536/](https://codertw.com/前端開發/290536/)

## function

```javascript
// 1.匿名函式(因為沒任何名稱,所以其他程式碼並沒有辦法呼叫他,所以要用就要重寫一次)
$(".guess_box").click(function(){
  xxxx;
});


// 2.具名函式(呼叫具名函式有以下兩種方式)
// A.函式宣告
function myFunc1()                 
{
  $("div").hide();
}
// 呼叫方法:
myFunc1();

// B.函式表達式
var myFunc2 = function()
{
  $("div").show();
}
// 呼叫方法(不需要()):
$("myElement").click(myFunc2);


$( document ).ready(function() {
  // 在這撰寫javascript程式碼
});
```

<https://melomelo1988.pixnet.net/blog/post/263934328>

<https://matthung0807.blogspot.com/2017/11/jquery-document-ready.html>

button事件觸發

```javascript
$("button#demo").click(function(){$("img").hide()})
```

<https://www.w3school.com.cn/jquery/jquery_ref_events.asp>

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/232048/](https://codertw.com/前端開發/232048/)

## window\.onload vs $(document).ready

ready：DOM下載完成就觸發function，啟動時機較早，前一次跟後一次所設定的函式都會被執行。

onload：除了DOM，連同其中的圖片影音的內容都下載完才會觸發function，啟動時機較晚，後一次所設定的函式會複寫上一次的。

<https://ithelp.ithome.com.tw/articles/10092601>

<https://matthung0807.blogspot.com/2017/11/jquery-document-ready.html>

```javascript
$( document ).ready(function() {
  // 在這撰寫javascript程式碼
});

# 若不放在ready當中則可能無法綁定到該物件，造成此行程式無效
$("#dom_id").html("123")
```

### 複寫

onload只會執行第二個，第一個會被忽略

[https://blog.xuite.net/coke750101/networkprogramming/31375424-%5BjQuery%5D%24%28document%29.ready%E5%92%8Conload%E4%BA%8B%E4%BB%B6%E7%9A%84%E5%B7%AE%E7%95%B0](https://blog.xuite.net/coke750101/networkprogramming/31375424-\[jQuery]%24%28document%29.ready和onload事件的差異)

```javascript
window.onload=function() {    
   alert('alert1');    
 };    

 window.onload=function() {    
   alert('alert2');    
 };
```

## setInterval

<https://neohsuxoops.blogspot.com/2018/04/ajaxfunction.html>

[https://kuro.tw/posts/2019/02/23/%E8%AB%87%E8%AB%87-JavaScript-%E7%9A%84-setTimeout-%E8%88%87-setInterval/](https://kuro.tw/posts/2019/02/23/談談-JavaScript-的-setTimeout-與-setInterval/)

[https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/276882/](https://codertw.com/前端開發/276882/)

## .html()  .text()  .val()

<http://androchen.blogspot.com/2013/04/jquery-html-text-val.html>

jQuery equivalent to “getElementsByName”

```javascript
$('[name="somenamehere"]');
```

<https://stackoverflow.com/questions/9711917/jquery-equivalent-to-getelementsbyname>

## 更新CSS

```javascript
$("#td_id").addClass('newClass')  //會累加，越來越長

$("#myParagraph").css({"backgroundColor": "black", "color": "white"});  //新增屬性
```

全域變數 vs 區域變數

1.變數宣告在function外面，不管有沒有加上var都是全域變數

2.變數宣告在function之內，沒有加上var就會成為全域變數

<https://engmeter.blogspot.com/2015/03/jqueryjquery.html>

## settimeout

```javascript
setTimeout(
  function() 
  {
    //do something special
  }, 5000);
)
```

## confirm

```javascript
var txt;
var r = confirm("Press a button!");
if (r == true) {
  txt = "You pressed OK!";
} else {
  txt = "You pressed Cancel!";
}
```

<https://www.w3schools.com/jsref/met_win_confirm.asp>

## textarea 的取值和給值

```javascript
var html=$("#desc").val();
$("#desc").val("write content");

if( $("#desc").val()==""){
    $("#desc").focus();
    alert("請務必填入回應內容");return false;
}
// 移除空格確定是否空值
if (!$.trim($("#desc").val())) {
   ..
}
```

<http://n.sfs.tw/content/index/10044>

<https://www.w3schools.com/tags/tag_textarea.asp>

## onchange event for input type=“number”

```javascript
$(":input").bind('keyup mouseup', function () {
    alert("changed");            
});
```

<https://stackoverflow.com/questions/9609731/onchange-event-for-input-type-number>

## 四捨五入

```javascript
function formatFloat(num, pos)
{
  var size = Math.pow(10, pos);
  return Math.round(num * size) / size;
}
alert(formatFloat("1109.1893", 2));
```

<https://ching119.pixnet.net/blog/post/59675573>

## preventDefault

防止url直接開啟，如：download

```javascript
$("a").click(function(event){
  event.preventDefault();
});
```

<https://www.w3school.com.cn/jquery/event_preventdefault.asp>
