如何編寫 jQuery 選擇器以使用 href 屬性查詢帶 # 的連結?


示例

你可以嘗試執行以下程式碼編寫一個 jQuery 選擇器來查詢 href 中包含 # 的連結。這裡,^ 用於查詢 href 中以 # 開頭的連結。

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

   $('a[href^="#"]').click(function(){
      alert('Success! Selected link starting with # in href.');
   });

});
</script>
</head>
<body>

<a href="#demo" title="new" >Demo</a><br>
<a href="/cplusplus/" title="C++ Tutorial" >C++</a>

</body>
</html>

更新時間:2019 年 12 月 18 日

3K+ 瀏覽量

開始你的職業 生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.