我使用 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/