简体   繁体   English

jQuery:不能只选择附加元素

[英]jQuery: Can't select just appended element

This is what happens on event:这是事件发生的情况:

$('div#pages').append($('<div class="page" id="test">...</div>'));

And then, on another event it fails doing this:然后,在另一个事件中,它无法执行此操作:

var page = $('div.page#test'); // returns empty array

I've debugged, and the appended html appears in the document structure after appending, but fails to get selected.我已经调试过了,附加的html在附加后出现在文档结构中,但是没有被选中。 Doing the same in browser console works perfectly.在浏览器控制台中执行相同的操作非常有效。
What could be the problem?可能是什么问题呢?

使用.find() http://api.jquery.com/find

var page = $('div#pages').find('div.page#test');

You just need to use live method:您只需要使用live方法:

$('.element').live('click', function(){
   alert($(this).html());
});

This is my solution that works fine for appended elements.这是我的解决方案,适用于附加元素。 在此处输入图片说明

Had the same issue, found that if I added the listener before adding the div, it wouldn't find the div.有同样的问题,发现如果我在添加div之前添加监听器,它不会找到div。 Make sure to add the listener after making the object.确保在创建对象后添加侦听器。

I had to use a hack to get around this problem recently when I was dynamically inserting <select> elements.我最近在动态插入<select>元素时不得不使用 hack 来解决这个问题。 I changed this:我改变了这个:

var $item = $('#appendedItem1'); // returns: []

to this:对此:

var $item = $(document.getElementById('appendedItem1')); // returns: [select#appendedItem1]

I know it seems like it should be the exact same thing, but only the second one works.我知道它看起来应该是完全一样的,但只有第二个有效。

This happens to me a lot more often than I would like.这种情况发生在我身上的频率比我希望的要高得多。 I've tried just about everything and while some solutions work in certain scenarios or browsers, they don't work in others.我已经尝试了几乎所有方法,虽然某些解决方案在某些场景或浏览器中有效,但在其他情况下却不起作用。 Some of the most common solutions I've tried were:我尝试过的一些最常见的解决方案是:

Waiting for DOM / element to be ready before selecting or manipulating it (this is so simple but actually works a lot of the time):在选择或操作之前等待 DOM / 元素准备好(这很简单,但实际上很多时候都有效):

$('#element').ready(() => {
    // Get or modify element
});

Using find (see CRABOLO's answer).使用find (参见 CRABOLO 的回答)。 Here is another example:这是另一个例子:

// Create element
let div = $('<div></div>');
// Use element to find child
let child = div.find('#element');
// Or
let child = $('#element', div);

If you're trying to listen to events triggered by an appended element, on should work for you most of the time since it can trigger for all future elements matching a selector (see Md Shahriar's answer).如果您正在尝试侦听由附加元素触发的事件,则大多数情况下on应该对您有用,因为它可以为匹配选择器的所有未来元素触发(请参阅 Md Shahriar 的回答)。 Here is another example:这是另一个例子:

$(document).on('event', '.element', function() {
    // "event" has been triggered on a ".element"
});

And an example from the documentation :以及文档中的一个示例:

$("body").on("click", "p", function() {
    alert($(this).text());
});

If none of the other solutions work for you , you can always try to check manually using an Interval .如果其他解决方案都不适合您,您可以随时尝试使用Interval手动检查。 This is the only way I've been able to solve this issue in certain situations:这是我在某些情况下能够解决此问题的唯一方法:

/* Usage:
   onEditable('#element', () => {
       // Element is now for sure ready to be selected or modified.
   });
*/
function onEditable(selector, callback){
    if($(selector)[0]){
        callback();
        return;
    }

    let s = setInterval(() => {
        // Check if jQuery can find the element
        if($(selector)[0]){
            // Call callback function
            clearInterval(s);
            callback();
        }
    }, 20);
}

I can't stress this enough;我再怎么强调也不为过; if you can find another solution that works for you, use that instead, since this doesn't work based on events and takes up a lot more computer resources.如果您能找到另一种适合您的解决方案,请改用它,因为这不会基于事件而起作用,并且会占用更多计算机资源。

Hope this helps someone having the same issues I did :).希望这可以帮助遇到与我相同问题的人:)。

missed quotes on class name page班级名称page上遗漏的引号

Also missed ) for append()也错过了) for append()

Should be应该

    $('div#pages').append($('<div class="page" id="test">...</div>'));

instead of代替

$('div#pages').append($('<div class=page id="test">...</div>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM