如何將 JavaScript 變數用於 jQuery 選擇器?


在 jQuery 選擇器中使用 JavaScript 變數非常簡單。

示例

我們來看一個使用 JavaScript 變數在 jQuery 中隱藏元素的例子

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("input").click(function(){
        var name = this.name;
      $("input[name=" + name + "]").hide();
    } );    
});
</script>
</head>
<body>

<h1>Heading 1</h1>
<input type="text" id="bx"/>
<input type="button" name="bx" value="one"/><br>
<input type="text" id="by"/>
<input type="button" name="by" value="two"/>
<p>To hide the buttons, click on it.</p>

</body>
</html>

更新於:2019 年 12 月 19 日

713 次瀏覽

開啟你的 職業 生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.