gpt4 book ai didi

javascript - JQuery 如何获取调用该函数的按钮的 ID

转载 作者:行者123 更新时间:2023-11-30 10:25:26 24 4
gpt4 key购买 nike

我有一个按钮 <button onclick="takedown()">当它被点击时,JQuery 将创建一个新按钮,其中包含输入和按钮中文本的 ID,当该按钮被点击时,它将调用一个函数 deltebutton()。这应该删除按钮,但我需要 JQuery 获取调用该函数的按钮的 ID,并将其设置为名为 id 的字符串。

我试过了 $(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();

}

如果有人知道如何做到这一点,那将非常有帮助。

最佳答案

不要在 JS 和 jQuery 中使用 String。你的选择器是错误的。

function deletenote(){
var id = event.target.id;
$('#'+id).remove();
}

此外,我认为您可以在不获取 ID 的情况下调用 remove。

function deletenote(){
$(this).remove();
}

关于javascript - JQuery 如何获取调用该函数的按钮的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com