追加后无法访问elment

时间:2016-02-07 18:24:36

标签: jquery

我正在使用追加将图片添加到<p id="p10">

$('#p10').append("<img src='plus.png' id='clicker' />");

我想引用我通过追加添加的图像添加切换:

$('#clicker').toggle(function() {
        // toggle code here
}, function() {
    // toggle code here
});

我无法通过id访问图像元素以使用切换。如果我注释掉切换,则图像会显示在页面上。一旦我添加了切换代码,图像就会闪烁一秒然后消失。

2 个答案:

答案 0 :(得分:0)

这是因为已经删除了接受应该以串行方式执行的函数参数的.toggle版本。 ( deprecated since v1.8, removed since 1.9

.toggle现在只显示/隐藏一个元素。因此,在点击器上调用.toggle只会隐藏它。

有关替代实施,请参阅What to use instead of `toggle(...)` in jQuery > 1.8?

答案 1 :(得分:0)

var imgTag = "<img>";
    imgTag.attr('src','plus.png');
    imgTag.attr('id','clicker');
    $('#p10').append(imgTag);

    $(imgTag).toggle(function() {
            // toggle code here
    }, function() {
        // toggle code here
    });
相关问题