Jquery:在.append中传递ID

时间:2014-10-24 00:56:41

标签: javascript jquery function selector identity

新手在这里得到了一个希望很简单的问题:

所以我有这行代码;

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

我需要通过&#34; &LT; img&gt; &#34;一个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'));

提前致谢

4 个答案:

答案 0 :(得分:2)

您可以将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/

答案 1 :(得分:0)

你可以通过:

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

答案 2 :(得分:0)

如果我理解正确,我就是这样做的:

$("#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/

答案 3 :(得分:0)

如果您对传递父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 */ 
    };
});