我有一个按钮<button onclick="takedown()">
,当点击它时,JQuery将在输入和按钮中创建一个带有文本id的新按钮,当点击该按钮时,它将调用一个函数deltebutton()
应该删除按钮,但是我需要JQuery来获取调用该函数的按钮的id并将其设置为名为id的String。
我尝试了$(event.target).attr('id');
和$(this).attr('id');
,但这两个都没有用
我瞪着它但却找不到任何东西。
这是函数
function takedown(){
note = document.getElementById("noteinput").value;
idh1 = note + "h1";
idbutton = note + "button";
idcenter = note + "center";
$('<center id="' +idcenter + '"> <h1 idh1="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
和
function deletenote(){
String id = $(event.target).attr('id');
$(id).remove();
}
如果有人知道如何做到这一点,那将非常有帮助。
答案 0 :(得分:3)
不要在JS和jQuery中使用String。你的选择器是错误的。
function deletenote(){
var id = event.target.id;
$('#'+id).remove();
}
另外我认为您可以在不获取ID的情况下调用删除。
function deletenote(){
$(this).remove();
}
答案 1 :(得分:1)
基于之前的答案和评论的更简单的解决方案将是:
function deletenote(){
$(event.target).remove();
}