JQuery:选择动态创建的元素并推送到Firebase

时间:2013-07-10 01:53:00

标签: jquery firebase dynamically-generated

所有这一切的初学者,玩Firebase。基本上,我想从Firebase检索文本条目,并在其旁边有一个“批准”按钮。单击该按钮时,我希望将特定文本条目推送到新的Firebase位置,并从页面中删除文本。我正在动态创建按钮和文本,我在选择按钮和我创建的div时遇到了一些麻烦。我知道我必须使用on(),但我不确定如何使用它。

谢谢!

approveRef.on('child_added', function(snapshot) {
 var posts = snapshot.val();
 $('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});

$('#approve').on("click", function(){
    var text = $('#post').val();
    postsRef.push({'text':text});
    $('#post').remove();

});

5 个答案:

答案 0 :(得分:23)

在加载时,您必须将.on()绑定到页面上已存在的动态添加元素的容器中,并将其设置为:

$('#yourContainer').on('click', '#approve', function(){
    //your code here..
});

答案 1 :(得分:5)

您的.on()无法正常工作,因为您正在动态添加按钮。您无法使用$('#approve')之类的元素ID选择器直接找到动态添加的元素。所以你应该 将.on()绑定到$(document)选择器。这将始终包含您动态添加的元素。

$(document).on( eventName, selector, function(){} );

$(document).on('click','#approve',function(){
//your code here
});

答案 2 :(得分:2)

另一种替代方法,更简单易懂,功能更强大,也非常有效,是在创建元素时简单地绑定事件:

approveRef.on('child_added', function(snapshot) {
 var posts = snapshot.val();
 var $button = $('<button style ="button" id="approve">Approve</button>');
 $button.on("click", function(){
    var text = $('#post').val();
    postsRef.push({'text':text});
    $('#post').remove();
 });

 $('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});

您将遇到的另一个问题是,假设您在页面中存在多个问题,那就是您在记录中使用ID。如果它们不是唯一的,它们就会发生冲突。

一个很好的选择是使用data- *标签或其他识别特征(例如css标签)来引用这些项目。但在你的情况下,你根本不需要它们!

approveRef.on('child_added', function(snapshot) {
 var posts = snapshot.val();
 var id = snapshot.name();

 var $button = $('<button style="button">Approve</button>');
 $button.on("click", function(){
    // use parent.closest(...) in place of an ID here!
    var text = $(this).parent().closest('textarea').val();
    postsRef.push({'text':text});
    $(this).parent().remove();
 });

 /* just an example of how to use a data-* tag; I could now refer to this element using:
    $('#feed').find('[data-record="'+id+'"]') if I needed to find it */
 $('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});

答案 3 :(得分:0)

我快速了解了DOM,然后又很方便地使用jQuery来解决此问题:

// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');

// This won't work...
$("#mynewthing")...

// But this will...
$(document.getElementByid("mynewthing"))...

此方法在turning the DOM object directly into a selector下有效。我喜欢它,因为这种方法在操作/意图上都是透明的。

答案 4 :(得分:0)

我不确定您在寻找什么。您可以使用.find()动态选择元素。我认为.find()会再次查看html结构以获取所需的元素。

$("#button").click(function(e){
   $(".parentContainer").find(".dynamically-child-element").html("Hello world");
});

$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event

这就是我的demo