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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17561243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:18:39  来源:igfitidea点击:

JQuery: Selecting dynamically created elements and pushing to Firebase

jqueryfirebasedynamically-generated

提问by Sam

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.

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

Thanks!

谢谢!

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();

});

回答by Nikko Reyes

You have to bind .on()on a container of your dynamically added element that is already on the page when you load it, and have it like this:

您必须.on()在加载时绑定到页面上已经存在的动态添加元素的容器上,并使其像这样:

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

回答by Keerthi

Your .on()didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should bind .on()with $(document)selector. This will always contain your dynamically added elements.

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

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

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

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

回答by Kato

Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:

另一种更容易理解、功能较弱但也完全有效的替代方法是在创建元素时简单地绑定事件:

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'));
});

Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.

您将遇到的另一个问题(假设页面上有多个此类)是您在记录中使用 ID。如果它们不是独一无二的,它们就会发生冲突。

A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!

一个很好的替代方法是使用 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'));
});

回答by Shaheed Haque

I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:

我发现快速深入 DOM,然后运行回 jQuery 非常方便解决这个问题:

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

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

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

This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.

这是通过将 DOM 对象直接转换为选择器来实现的。我喜欢它,因为这种方法在操作/意图上是透明的。

回答by QDinh

I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.

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

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

Or

或者

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

So this is my demo

所以这是我的演示