如何在jQuery选择器中使用JavaScript变量?


160

如何使用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等于被单击的元素的名称。

Answers:


243
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();
});

2
重要的是要注意,用于连接的变量必须是非数字的,如果id是数字,则toString()也是这样。
isync

IE 11不喜欢这样,$('#'+ id).hide();,它是未定义的。
Welshboy

55
$(`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"淡出一组元素。


14
$("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();



2
  1. ES6字符串模板

    如果您不需要IE / EDGE支持,这是一种简单的方法

    $(`input[id=${x}]`).hide();

    要么

    $(`input[id=${$(this).attr("name")}]`).hide();

    这是一个es6功能,称为模板字符串


  1. 字符串串联

    如果您需要IE / EDGE支持,请使用

    $("#" + $(this).attr("name")).hide();


  1. 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();

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.