### [How to pass parameters in GET requests with jQuery](https://stackoverflow.com/questions/15576548/how-to-pass-parameters-in-get-requests-with-jquery )
```js
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
headers: {
'Authorization': 'Bearer your_token'
},
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
```
### How to pass json in POST request with jQuery
```js
var dataJson = {};
dataJson["title"] = $("#title").val();
dataJson["subtitle"] = $("#subtitle").val();
dataJson["value"] = $("#markdowncontent").val();
$.ajax({
url: "ajax.aspx",
type: "post",
data: JSON.stringify(dataJson),
contentType: "application/json;charset=utf-8",
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
```
---
將所有 table 新增 display class
```js
$('table').addClass("display");
```
對所有 a tag,若為 https:// 開頭則增加 target _blank 欄位
```js
$('a[href^="https://"]').attr('target','_blank');
```
### [Selectors](https://www.w3schools.com/jquery/jquery_ref_selectors.asp)
[選擇器 (selector)](https://ithelp.ithome.com.tw/articles/10095237)
```js
// jQuery 有三個最重要的選擇器,如下:
$("p") // 選出所有 <p> </p>的節點
$("#divId") // 選出所有 <div id=”divId”></div> 的節點
$(".divClass") // 選出所有 <div class=”divClass”></div> 的節點
$("div[id]"); //選擇所有含有id屬性的div元素
$("input[name='Jack']"); //選擇所有的name屬性等於’Jack’的input元素
$("input[name!='Jack']"); //選擇所有的name屬性不等於’Jack’的input元素
$("input[name^='J']"); //選擇所有的name屬性以’J'開頭的input元素
$("input[name$='K']"); //選擇所有的name屬性以’k'結尾的input元素
$("input[name*='ck']"); //選擇所有的name屬性包含’ck’的input元素
$("input[id][name$='man']"); //可以使用多個屬性進行聯合選擇,該選擇器是得到所有的含有id屬性並且那麼屬性以man結尾的元素
$('input[name="a"][value="3"]').attr('id'); // jquery 選擇 name=a 且 value=3 並找出 id
// 階層屬性有以下四種:
$('#div1 p').addClass('d1'); // 物件中的某一種物件(空白)
$('#div1 *').addClass('d1'); // 物件中的所有物件(*)
$('#div1 + p').addClass('d1'); // 之後符合條件的第一個(+)
$('#div1 ~ p').addClass('d1'); // 之後符合的所有(~)
```
### [DataTables](https://ithelp.ithome.com.tw/articles/10272439)
```html
<!-- CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<!-- jq -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
```
```js
$(document).ready( function () {
$('#table_id').DataTable();
} );
```
### [How to pass arguments properly to Pass functions](https://cmorinan.medium.com/passing-functions-as-arguments-in-javascript-tips-and-pitfalls-d29bbd4522a9)
```js
function openLinkWhenCtrl(url){
if (!window.event.ctrlKey) {
return;
}
window.open(url, '_blank');
}
var url = $(md).find("thead").find("a").attr("href");
$(md).find("td").click(() => openLinkWhenCtrl(url));
```
### [Add element](https://www.w3schools.com/jquery/jquery_dom_add.asp)
```js
function appendText() {
var txt1 = "<p>Text.</p>"; // Create element with HTML
var txt2 = $("<p></p>").text("Text."); // Create with jQuery
var txt3 = document.createElement("p"); // Create with DOM
txt3.innerHTML = "Text.";
$("body").append(txt1, txt2, txt3); // Append the new elements
}
function afterText() {
var txt1 = "<b>I </b>"; // Create element with HTML
var txt2 = $("<i></i>").text("love "); // Create with jQuery
var txt3 = document.createElement("b"); // Create with DOM
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2, txt3); // Insert new elements after <img>
}
```
### [Set Content and Attributes](https://www.w3schools.com/jquery/jquery_dom_set.asp)
```js
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
$("button").click(function(){
$("#w3s").attr("href", "https://www.w3schools.com/jquery/");
});
$("button").click(function(){
$("#w3s").attr({
"href" : "https://www.w3schools.com/jquery/",
"title" : "W3Schools jQuery Tutorial"
});
});
```
### [Get and Set CSS Classes](https://www.w3schools.com/jquery/jquery_css_classes.asp)
```js
$("button").click(function(){
$("#div1").addClass("important blue");
});
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
$("p").css("background-color");
$("p").css({"background-color": "yellow", "font-size": "200%"});
```
### jquery 元件的隱藏及顯示
使用jQuery來控制元件的隱藏及顯示非常簡單。你可以使用以下的方法來實現:
1. 隱藏元件:
```javascript
$('#elementId').hide();
```
這個方法會將指定的元件隱藏起來。你也可以使用`fadeOut()`方法來實現淡出效果:
```javascript
$('#elementId').fadeOut();
```
2. 顯示元件:
```javascript
$('#elementId').show();
```
這個方法會將指定的元件顯示出來。你也可以使用`fadeIn()`方法來實現淡入效果:
```javascript
$('#elementId').fadeIn();
```
3. 切換元件的顯示狀態:
如果你想要在點擊元素時切換其顯示狀態,你可以使用`toggle()`方法:
```javascript
$('#toggleBtn').click(function(){
$('#elementId').toggle();
});
```
# json to checkbox
以下範例示範,如何用 jQuery 將一個 JSON 陣列動態產生一組 checkbox 並加到指定的 `<div>` 中。
步驟摘要
1. 在 HTML 中放一個空的容器 `<div>`。
2. 準備你的 JSON 陣列(也可以來自 AJAX 呼叫)。
3. 用 jQuery 迴圈走訪 JSON,動態建立 `<input type="checkbox">` 及對應 `<label>`,再 append 到容器。
範例程式碼
```html
<!DOCTYPE html>
<html lang="zh-tw">
<head>
<meta charset="UTF-8">
<title>jQuery JSON 產生 Checkbox 範例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- 1. 準備一個容器 -->
<div id="checkboxContainer"></div>
<script>
$(function(){
// 2. 假設這是你的 JSON 陣列,通常可以 $.getJSON() 拿到
var data = [
{ id: 1, label: '選項 A', checked: true },
{ id: 2, label: '選項 B', checked: false },
{ id: 3, label: '選項 C', checked: false }
];
// 3. 清空容器(如果有必要)
$('#checkboxContainer').empty();
// 4. 迴圈動態產生 checkbox + label
$.each(data, function(idx, item){
// 建 checkbox
var $chk = $('<input/>', {
type: 'checkbox',
id: 'chk_' + item.id, // 給個唯一 id
name: 'myCheckbox', // name 屬性
value: item.id,
checked: item.checked // 預設是否勾選
});
// 建對應的 label
var $lbl = $('<label/>', {
for: 'chk_' + item.id,
text: item.label
});
// 把 checkbox + label 加到容器裡,並換行
$('#checkboxContainer')
.append($chk)
.append($lbl)
.append('<br>');
});
});
</script>
</body>
</html>
```
進階:從遠端 API 拿 JSON
```js
$(function(){
$.getJSON('/api/options', function(data){
var $c = $('#checkboxContainer').empty();
$.each(data, function(i, item){
$('<input>', {
type: 'checkbox',
id: 'chk_' + item.id,
value: item.id,
checked: item.checked
})
.add( $('<label>', { for: 'chk_' + item.id, text: item.label }) )
.appendTo($c)
.last().after('<br>');
});
});
});
```
說明
- $.each(data, ...):走訪陣列中每個物件
- $('\<input/\>',{…}):用物件語法快速設定屬性
- .appendTo() 或 .append():把元素插入到指定容器
- .empty():先清空避免重複
這樣就能自動把 JSON 轉成 checkbox 並放進指定的 div 了。希望對你有幫助!
# 上傳圖片
以下範例示範如何用 jQuery+AJAX 上傳圖片,並在上傳前做預覽。範例分成兩部分:
1. 前端 (HTML + jQuery)
2. 後端 (以 PHP 為例)
---
## 1. 前端:HTML + jQuery
```html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>jQuery 圖片上傳範例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#preview { max-width: 300px; max-height: 300px; margin-top: 10px; }
</style>
</head>
<body>
<h2>圖片上傳+預覽 Demo</h2>
<form id="uploadForm">
<input type="file" id="fileInput" name="image" accept="image/*">
<br>
<img id="preview" src="#" alt="預覽" style="display:none;">
<br>
<button type="submit">上傳</button>
</form>
<div id="result"></div>
<script>
$(function(){
// 1. 選檔時顯示預覽
$('#fileInput').on('change', function(){
const file = this.files[0];
if (!file) return;
// 只接受影像
if (!file.type.match('image.*')) {
alert('請選擇圖片檔案');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
$('#preview').attr('src', e.target.result).show();
};
reader.readAsDataURL(file);
});
// 2. 表單送出時以 AJAX 上傳
$('#uploadForm').on('submit', function(e){
e.preventDefault();
const fileInput = $('#fileInput')[0];
if (fileInput.files.length === 0) {
alert('請先選擇檔案');
return;
}
// 建立 FormData 物件,將檔案與其他欄位加入
const formData = new FormData();
formData.append('image', fileInput.files[0]);
$.ajax({
url: 'upload.php', // 後端上傳處理程式
type: 'POST',
data: formData,
contentType: false, // 告訴 jQuery 不要去設定 Content-Type
processData: false, // 告訴 jQuery 不要去處理 data
dataType: 'json', // 預期回傳 JSON
success: function(res) {
if (res.success) {
$('#result').html(
'<p>上傳成功!檔案位置:<a href="' + res.url + '" target="_blank">' +
res.url + '</a></p>'
);
} else {
$('#result').text('上傳失敗:' + res.error);
}
},
error: function(xhr, status, err) {
$('#result').text('AJAX 發生錯誤:' + err);
}
});
});
});
</script>
</body>
</html>
```
說明:
- `FormData` 可讓你在 AJAX 請求裡面傳送檔案。
- `contentType: false`、`processData: false` 是上傳檔案時必備設定。
- 用 `FileReader` 讀取檔案後顯示在 `<img>` 做預覽。
---
## 2. 後端(PHP 範例:upload.php)
```php
<?php
header('Content-Type: application/json');
// 確認是否有檔案上傳
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
echo json_encode([
'success' => false,
'error' => '沒有收到檔案,或是上傳錯誤。'
]);
exit;
}
$uploadDir = __DIR__ . '/uploads/';
// 建立目錄(若不存在)
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 取得原檔名與暫存檔路徑
$tmpName = $_FILES['image']['tmp_name'];
$originalName = basename($_FILES['image']['name']);
// 可以自行改檔名避免衝突
$targetFile = $uploadDir . time() . '_' . $originalName;
// 移動檔案到正式位置
if (move_uploaded_file($tmpName, $targetFile)) {
// 回傳前端可存取的 URL
$urlPath = 'uploads/' . basename($targetFile);
echo json_encode([
'success' => true,
'url' => $urlPath
]);
} else {
echo json_encode([
'success' => false,
'error' => '檔案移動失敗'
]);
}
?>
```
注意:
1. `uploads/` 資料夾需可寫入(chmod 755/775/777 視伺服器設定而定)。
2. 實務上建議再做檔案類型、大小檢查,或更嚴格的安全驗證。
---
這樣就完成了一個簡單的 jQuery 圖片上傳+預覽範例!如果你後端是 Node.js、ASP.NET MVC、Java 等,只要路由改成對應後端,並在後端用對應語法處理 `multipart/form-data` 即可。