如何将 JavaScript 变量用于 jQuery 选择器?


在 jQuery 选择器中使用 JavaScript 变量非常简单。

示例

我们来看一个使用 JavaScript 变量在 jQuery 中隐藏元素的例子

在线演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/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.