Jquery:在.append中传递ID

Jquery: Passing ID inside .append

本文关键字:ID append Jquery      更新时间:2023-09-26

这里的新手收到了一个问题,希望它足够简单:

所以我有这行代码;

            $("#r"+i+"c"+j).append($("<img>", {style:"display:block; margin: 0 auto;", src: imagefile, width: cellDimension + "px", height: cellDimension + "px"}));

我需要传递"<img>"一个ID,以便在单独的函数中与它交互。尝试过以下方法:

            $("#"+ID+"<img>",

            $("#r"+i+"c"+j).append($("<img>", {style:"display:block; margin: 0 auto;", src: imagefile, width: cellDimension + "px", height: cellDimension + "px"}).attr('ID'));

提前感谢

您可以将id作为创建图像时传递的对象的属性来传递。

$("<img>", {
    style:"display:block; margin: 0 auto;",
    src: imagefile,
    width: cellDimension + "px",
    height: cellDimension + "px",
    id: ID_HERE } // ID here - either a string variable, or string literal like "imageId"
);

演示:http://jsfiddle.net/dmpd9a64/

此外,您可以使用attr传递一个值,如下所示:

$("<img>", {
    style:"display:block; margin: 0 auto;",
    src: imagefile,
    width: cellDimension + "px",
    height: cellDimension + "px"}
).attr('id', ID_HERE); // again, string variable or literal

演示:http://jsfiddle.net/dmpd9a64/1/

如果您有兴趣传递父ID,使其成为图像ID的一部分,下面是如何做到的:

$("#r" + i + "c" + j).append( function() { 
    return $("<img>", {
        //any attributes you'd like to set, such as:
        class: 'new-image',
        'data-id': this.id,
        id: this.id + '-something' /* since IDs must be unique */ 
    };
});

您可以通过:

    $("#r"+i+"c"+j).append($("<img id='"+yourID+"'>", {style:"display:block; margin: 0 auto;", src: imagefile, width: cellDimension + "px", height: cellDimension + "px"}));

如果我正确理解你,我会这样做:

$("#r" + i + "c" + j).append($("<img>", {
    style: "display:block; margin: 0 auto;",
    src: imagefile,
    width: cellDimension + "px",
    height: cellDimension + "px",
    id: id 
}));

以下是工作代码:http://jsfiddle.net/silkster/jqqLmm46/