Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法检索动态创建的div的id_Javascript_Jquery_Html - Fatal编程技术网

Javascript 无法检索动态创建的div的id

Javascript 无法检索动态创建的div的id,javascript,jquery,html,Javascript,Jquery,Html,我已经创建了一个动态div,以及表…我希望当我单击div中的图像时,它会给出我单击的div的id…下面是代码。请任何人指出错误在哪里。。。!?在警报框中,我无法获取div的id 下面的代码创建div function create_newGrid() { //create div for corresponding table var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab" + nooftables

我已经创建了一个动态div,以及表…我希望当我单击div中的图像时,它会给出我单击的div的id…下面是代码。请任何人指出错误在哪里。。。!?在警报框中,我无法获取div的id

下面的代码创建div

function create_newGrid() {
    //create div for corresponding table
    var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab" + nooftables });
    var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", "onclick": "openTableSettings(this);" })
    $(tableDiv).append(divImage);
    // append grid to designer
    $(document.getElementById("center")).append(tableDiv);
    $(document.getElementById("center")).append(table);
}

如果你这样做也许会更好

var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", class: "clickable"});
(假设jQuery>=1.7)

尝试以下方法:

$("div > img").click(function() { 
    id = $(this).parent("div").attr("id");
    alert(id);    
})

问题是图像上的onclick没有ID。如果在浏览器控制台中运行此操作,它将在此页面底部添加一个带有文本的div,您可以看到正确检索ID。(您的代码已修改)

//为相应的表创建div
var tableDiv=$('').attr({“id”:“settingsDiv选项卡”,“onclick”:“警报($(this.attr('id'));”);
var divImage=$(“这是一大串文本”

”); tableDiv.append(divImage); $(document.body).append(tableDiv);
您正在将对img的引用传递到
openTableSettings()
。使用
.closest()
获取div:

function openTableSettings(img) { 
    alert($(img).closest("div").attr("id")); 
} 

o是的,我知道了……我必须获取图像的父元素才能获取图像的id\n没问题,测试这样的代码最简单的方法就是将其转储到chrome或ff之类的控制台中。给出了如何使用控制台在此页面上测试它的示例:)
$("div > img").click(function() { 
    id = $(this).parent("div").attr("id");
    alert(id);    
})
//create div for corresponding table
var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab", "onclick": "alert($(this).attr('id'));"});
var divImage = $('<p>this is a big bunch of text</p>');
tableDiv.append(divImage);
$(document.body).append(tableDiv);
function openTableSettings(img) { 
    alert($(img).closest("div").attr("id")); 
}