简体   繁体   English

jQuery .remove使用变量作为选择器

[英]jquery .remove use a variable as selector

I have a variable packet 我有一个可变的小包

var packet = ""

and overtime the user presses a button it adds the letter a to the variable 并且用户按下按钮会超时,它将字母a添加到变量中

packet =  packet + "a"

it also places a div with the id of the variables value so i have 3 divs each with different ids 它还将div与变量值的id放置在一起,所以我有3个div,每个div具有不同的id

<div id="a"></div>
<div id="aa"></div>
<div id="aaa"></div>

and then another button calls a function 然后另一个按钮调用一个函数

function open() {
packet = packet - "a"
$('#'+packet).remove();
}

but when this function is called it doesn't remove the divs at all. 但是调用此函数时,它根本不会删除div。 i want the divs to be removed in the order they were added. 我希望按照添加顺序删除div。 I have tried doing classes and having a dot instead of the # and i have tried just putting the variable there 我试过做类并用点代替#,并且尝试将变量放在那

I think i have done something wrong with how i use the selector? 我认为我在使用选择器方面做错了什么?

Replace in your open function 替换您的打开功能

packet = packet - "a"

With this : 有了这个 :

packet = packet.slice(0, -1);

你需要

packet = packet.substring(0, packet.length - 1)

You need to use + for string concatenation in JavaScript 您需要在JavaScript中使用+进行字符串连接

 var packet = ''; $('#btn').click(function() { packet += 'a'; $('#' + packet).remove(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="a">a</div> <div id="aa">aa</div> <div id="aaa">aaa</div> <button id=btn>click</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM