jquery - 在 jQuery 中实时查找

标签 jquery find live

我使用 jQuery 中的 find 方法来查找页面上的特定框。

我还有其他按钮可以创建新框而无需刷新页面。 find 找不到这些新框,这是一个问题。

我使用:

$("fieldset#"+new_item_id).find("div.images").append(img);

但我也在考虑如何实现 live 方法。或者我应该使用 on 或其他?这种实时更新的东西很难。

最佳答案

您必须对每个事件调用一个函数才能实现此目的。

function addImg( new_item_id, img ){
    $("fieldset#"+new_item_id).find("div.images").append(img);
}

对于那些已经存在的元素,您必须在页面加载时调用它。对于每个添加的元素,您再次调用它。所以你最终会得到类似的结果:

$(function(){
    $("fieldset[id]").each(function(){
        var img = //how ever you find this image...
        addImg($(this).attr('id'),img);
    });

    $('button').click(function(){
        //some ajax call
        $.ajax(
            // what ever options you have for url, data etc etc.
            success: function(response){ // assuming response is just the markup
                var $el = $(response);
                $('#content').append($el); // how ever you add this content - its probably NOT #content but you'll know that...
                var img = //how ever you find this image...
                addImg( $el.attr('id'), img );
            }
        );
    });
});

function addImg( new_item_id, img ){
    $("#"+new_item_id).find("div.images").append(img);
}

编辑 - 而不是让函数找到元素,只需将其传递进去...

$(function(){
    $("fieldset[id]").each(function(){
        var img = //how ever you find this image...
        addImg($(this),img);
    });

    $('button').click(function(){
        //some ajax call
        $.ajax(
            // what ever options you have for url, data etc etc.
            success: function(response){ // assuming response is just the markup
                var $el = $(response);
                $('#content').append($el); // how ever you add this content - its probably NOT #content but you'll know that...
                var img = //how ever you find this image...
                addImg( $el, img );
            }
        );
    });
});

function addImg( $newEle, img ){
    $newEle.find("div.images").append(img);
}

关于jquery - 在 jQuery 中实时查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15407632/

相关文章:

javascript - 无法将ajax变量传递给php

javascript - 如何在加载的页面上创建多个 select-2

regex - 正则表达式非结尾词linux终端

javascript - jQuery live() 函数用于网站大量使用 ajax

javascript - jQuery 1.9 .live() 不是函数

javascript - jQuery ("#portfolioslide").data ("AnythingSlider") 为空

php - Jquery Uploadify 图像多个实例并调用每个实例完成前一个实例

linux - 删除目录中的所有文件而不删除符号链接(symbolic link)及其指向的文件

linux - 重命名子文件夹

Jquery 注册点击未点击的元素的奇怪行为