如何在jquery选择器中使用javascript变量

use*_*269 148 javascript jquery

如何将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"/>
Run Code Online (Sandbox Code Playgroud)

基本上我想要做的是能够隐藏id等于被点击元素名称的元素.

Vin*_*ins 223

var name = this.name;
$("input[name=" + name + "]").hide();
Run Code Online (Sandbox Code Playgroud)

或者你可以做这样的事情.

var id = this.id;
$('#' + id).hide();
Run Code Online (Sandbox Code Playgroud)

或者你也可以给一些效果.

$("#" + this.id).slideUp();
Run Code Online (Sandbox Code Playgroud)

如果要从页面中永久删除整个元素.

$("#" + this.id).remove();
Run Code Online (Sandbox Code Playgroud)

你也可以在这里使用它.

$("#" + this.id).slideUp('slow', function (){
    $("#" + this.id).remove();
});
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,用于连接的变量必须是非数字的,因此如果 id 是数字,则执行 toString() 。 (2认同)

Phi*_*hil 55

$(`input[id="${this.name}"]`).hide();
Run Code Online (Sandbox Code Playgroud)

当您使用ID时,这会表现得更好

$(`#${this.name}`).hide();
Run Code Online (Sandbox Code Playgroud)

我强烈建议您通过按钮点击隐藏元素的方法更具体.我会选择使用数据属性.例如

<input id="bx" type="text">
<button type="button" data-target="#bx" data-method="hide">Hide some input</button>
Run Code Online (Sandbox Code Playgroud)

然后,在你的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]();
});
Run Code Online (Sandbox Code Playgroud)

现在,您可以完全控制您要定位的元素以及通过HTML发生的事情.例如,您可以使用data-target=".some-class"data-method="fadeOut"淡出一组元素.


Ale*_*che 13

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   
Run Code Online (Sandbox Code Playgroud)

也适用于ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
Run Code Online (Sandbox Code Playgroud)

什么时候,(有时)

$('input#' + id).hide();
Run Code Online (Sandbox Code Playgroud)

不工作,因为它应该.

你甚至可以做到这两点:

$('input[name="' + name + '"][id="' + id + '"]').hide();
Run Code Online (Sandbox Code Playgroud)


Ale*_* R. 7

var x = $(this).attr("name");
$("#" + x).hide();
Run Code Online (Sandbox Code Playgroud)


mor*_*gar 5

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