Jquery 与脚本一起添加的div元素(按钮)出现并运行,但attributeRes返回未定义

Jquery 与脚本一起添加的div元素(按钮)出现并运行,但attributeRes返回未定义,jquery,undefined,element,innerhtml,Jquery,Undefined,Element,Innerhtml,此代码根据在其他位置选中的输入复选框填充catSelectedDiv .removeUpdateButtons div是使用innerHTML添加的,它们看起来和似乎都正常工作。也就是说,它们的onclick函数被调用,CSS中的悬停动作也可以工作 但是,我需要将它们的ID传递给click函数,以便按钮click可以取消选中相应的复选框 代码的业务端是输出+=行 如图所示,警报提供未定义的。该警报还提供未定义的类或甚至.parent的ID/类等选项 function clickInput() /

此代码根据在其他位置选中的输入复选框填充catSelectedDiv

.removeUpdateButtons div是使用innerHTML添加的,它们看起来和似乎都正常工作。也就是说,它们的onclick函数被调用,CSS中的悬停动作也可以工作

但是,我需要将它们的ID传递给click函数,以便按钮click可以取消选中相应的复选框

代码的业务端是输出+=行

如图所示,警报提供未定义的。该警报还提供未定义的类或甚至.parent的ID/类等选项

function clickInput() //for category check box list
{
    var inputSet = document.getElementsByClassName("catInput"); //these are the category checkboxes
    var thisInput;
    var outPut = "";
    var thisLabel;
    for (thisInput = 0; thisInput < inputSet.length; thisInput++)
    {
        if (inputSet[thisInput].checked)
        {
            thisLabel = document.getElementById("L" + inputSet[thisInput].id);
            outPut += '<div id="X' + inputSet[thisInput].id + '" class="removeUpdateButtons" onclick="clickXButton()"></div>' + (thisLabel.innerText || thisLabel.textContent) + '</br>';
        };
    };
    document.getElementById("catSelectedDiv").innerHTML = outPut;
    return;
};

function clickXButton()
{
    alert($(this).attr("id"));
};
我需要的是在onclick fn代码中获得每个div/按钮的标识信息。谢谢。

用onclick=clickXButton回复onclick=clickXButton这个。并将您的功能更改为: 功能点击按钮{ 警报$el.attrid;
};

您的代码应该是这样的

function clickInput() //for category check box list
{
    var inputSet = document.getElementsByClassName("catInput"); //these are the category checkboxes
    var thisInput;
    var outPut = "";
    var thisLabel;
    for (thisInput = 0; thisInput < inputSet.length; thisInput++)
    {
        if (inputSet[thisInput].checked)
        {
            thisLabel = document.getElementById("L" + inputSet[thisInput].id);
            outPut += '<div id="X' + inputSet[thisInput].id + '" class="removeUpdateButtons" onclick="clickXButton(this)"></div>' + (thisLabel.innerText || thisLabel.textContent) + '</br>';
        };
    };
    document.getElementById("catSelectedDiv").innerHTML = outPut;
    return;
};

function clickXButton(obj)
{
    alert($(obj).attr("id"));
};

jQuery提供了一种更好的设置事件处理程序的方法。在这种情况下,它将是:

...
// remove the onclick handler here
outPut += '<div id="X' + inputSet[thisInput].id + '" class="removeUpdateButtons"></div>' + (thisLabel.innerText || thisLabel.textContent) + '</br>';
...

$(document).on("click", "#catSelectedDiv .removeUpdateButtons", function() {
    alert($(this).attr("id"));
});

含糖的成功了。如果你不介意教育我,我怎么知道我所拥有的会失败呢。我在硬编码的“按钮”集合中使用了类似的共享功能,它工作得很好。无论如何,谢谢!