如何使用JavaScript变量作为jQuery选择器中的参数?
<script type="text/javascript">
$(function(){
$("input").click(function(){
var x = $(this).attr("name");
$("input[id=x]").hide();
});
});
</script>
<input type="text" id="bx"/><input type="button" name="bx"/>
<input type="text" id="by"/><input type="button" name="by"/>
基本上,我想做的就是能够隐藏一个元素,该元素id
等于被单击的元素的名称。
var name = this.name;
$("input[name=" + name + "]").hide();
或者,您可以执行以下操作。
var id = this.id;
$('#' + id).hide();
或者,您也可以发挥作用。
$("#" + this.id).slideUp();
如果要删除整个元素,请从页面中永久删除。
$("#" + this.id).remove();
您也可以在此使用它。
$("#" + this.id).slideUp('slow', function (){
$("#" + this.id).remove();
});
$(`input[id="${this.name}"]`).hide();
由于您使用的是ID,因此效果会更好
$(`#${this.name}`).hide();
我强烈建议您更具体地说明通过单击按钮隐藏元素的方法。我会选择使用数据属性。例如
<input id="bx" type="text">
<button type="button" data-target="#bx" data-method="hide">Hide some input</button>
然后,在您的JavaScript中
// using event delegation so no need to wrap it in .ready()
$(document).on('click', 'button[data-target]', function() {
var $this = $(this),
target = $($this.data('target')),
method = $this.data('method') || 'hide';
target[method]();
});
现在,您可以通过HTML完全控制定位的元素以及该元素的作用。例如,您可以使用data-target=".some-class"
和data-method="fadeOut"
淡出一组元素。
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
也可用于ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
何时(有时)
$('input#' + id).hide();
不工作,因为它应该。
您甚至都可以:
$('input[name="' + name + '"][id="' + id + '"]').hide();
var x = $(this).attr("name");
$("#" + x).hide();
$("#" + $(this).attr("name")).hide();
-
ES6字符串模板
如果您不需要IE / EDGE支持,这是一种简单的方法
$(`input[id=${x}]`).hide();
要么
$(`input[id=${$(this).attr("name")}]`).hide();
这是一个称为模板字符串的es6功能
-
字符串串联
如果您需要IE / EDGE支持,请使用
$("#" + $(this).attr("name")).hide();
-
DOM中的选择器作为数据属性
这是我的首选方式,因为它使您的代码真正干燥
// HTML <input type="text" id="bx" /> <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/> //JS $($(this).data("input-sel")).hide();
本文地址:http://javascript.askforanswer.com/ruhezaijqueryxuanzeqizhongshiyongjavascriptbianliang.html
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!