jQuery語法
- 基礎(chǔ)語法:$(selector).action(),美元符號定義jQuery,選擇符selector查詢和查找HTML元素,jQuery的action()執(zhí)行對元素的操作
- 引入jQuery
<script src="jquery-3.3.1.min.js"></script>
- 文檔加載完畢
$(document).ready(function () {
alert("文檔加載完畢");
});
- 點(diǎn)擊某個(gè)p元素即會(huì)隱藏其顯示的內(nèi)容
$(document).ready(function () {
$("p").click(function () {
$(this).hide();
})
});
jQuery選擇器
- 元素選擇器,指定元素進(jìn)行修改,點(diǎn)擊按鈕修改p中的內(nèi)容
$(document).ready(function () {
$("button").click(function () {
$("p").text("修改");
});
});
- id選擇器
$("#pid").text("修改");
- 類選擇器
$(".pclass").text("修改");
- 選擇器的變動(dòng)類似于css中的變動(dòng)
jQuery事件
- 事件常用方法:點(diǎn)擊事件,雙擊取消按鈕,鼠標(biāo)移上mouseenter,鼠標(biāo)移開mouseleave其他事件方法可以查看API
$(document).ready(function () {
$("button").dblclick(function () {
$(this).hide();
});
});
- on事件綁定,或者使用bind
$(document).ready(function () {
$ ("#btn").on("click",clickHander1);
});
function clickHander1() {
console.log("clickHander1")
}
- off解除綁定或者unbind
$(document).ready(function () {
$ ("#btn").on("click",clickHander1);
$ ("#btn").on("click",clickHander2);
$ ("#btn").off("click",clickHander2);
});
- 事件目標(biāo)
$(document).ready(function () {
$("body").on("click",bh);
$("div").on("click",dh);
});
function bh(event) {
console.log(event)
}
- 事件冒泡,阻止父級事件冒泡,使本次事件停止執(zhí)行
event.stopPropagation()
- 阻止所有事件冒泡,使用后自此以下事件均停止執(zhí)行
function dh(event) {
console.log(event)
event.stopImmediatePropagation()
}
- 自定義事件,通過jQuery添加一個(gè)自定義事件btn,通過trigger()方法觸發(fā)自定義事件
var btn;
$(document).ready(function () {
btn=$("#btn");
btn.click(function () {
var e=jQuery.Event("MyEvent");
btn.trigger(e);
});
btn.on("MyEvent",function (event) {
console.log(event);
});
});
捕獲HTML內(nèi)容
- text()方法,獲得id為pid的標(biāo)簽中的內(nèi)容
$(document).ready(function () {
$("#btn").click(function () {
alert("text:"+$("#pid").text());
});
});
- 若使用html()方法可以得到元素里的所有內(nèi)容,包括標(biāo)簽顯示
alert("text:"+$("#pid").html());
- val()方法可以獲取輸入字段的值,比如文本框中的內(nèi)容
$(document).ready(function () {
$("#btn").click(function () {
alert("text:"+$("#iid").val());});
});
- attr()獲取元素的屬性,獲取a標(biāo)簽的鏈接屬性
alert("text:"+$("#aid").attr("href"));
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。