谁能向我解释为什么这个jquery函数不起作用?

Can anybody explain to me why this jquery function does not work?

提问人:backups 提问时间:11/13/2023 最后编辑:backups 更新时间:11/13/2023 访问量:45

问:

我制作了一个简单的代码示例来缩小我的问题范围。

如果我有这个代码

jQuery.noConflict();
    jQuery(document).ready(function($) {
    var dosomething=function(the_selector){
        $('.content', the_selector).each(function() {
            $(this).css('background-color','red');
        });
    }
    dosomething('.flickr_badge_image');
});

它不起作用,但如果我将其更改为

jQuery.noConflict();
jQuery(document).ready(function($) {
    var dosomething=function(the_selector){
        $(the_selector).each(function() {
            $(this).css('background-color','red');
        });
    }
    dosomething('.flickr_badge_image');
});    

它有效

那么为什么我不能将 2 个类('.content',the_selector)合并到一个调用中呢?我曾经能够在jQuery中做到这一点。但不知何故,它停止了工作?

$('.content',the_selector).each(function() {
    jQuery(this).css('background-color','red');
});

当然,我可以调用dosomething('.content,.flickr_badge_image');

但我想了解为什么它不能像我现在做事那样工作。

为什么它不起作用?我在这里错过了什么?

感谢您的任何反馈

jQuery 元素

评论

3赞 Nico Haase 11/13/2023
您能否共享所涉及的标记,以便其他人可以尝试重现该问题?
0赞 phuzi 11/13/2023
我们需要看到一个适当的标记示例。
0赞 freedomn-m 11/13/2023
我缺少什么 - 文档?:)api.jquery.com/jquery/#jQuery-selector-context - 所以与 - 相同 - 即需要是 的子项。如果没有 HTML,很难判断您是想让the_selector成为 .content 的子级,还是两者都想要。jQuery(selector, context)$('.content', the_selector)$(the_selector).find('.content').contentthe_selector

答:

0赞 trincot 11/13/2023 #1

$('.content', the_selector)将在匹配的节点下方查找,而您似乎想用 扩展。.contentthe_selectorthe_selector.content

在这种情况下,您有多种选择,包括:

  • 使用 jQuery:$('.content').add(the_selector)
  • 构建一个新的选择器:$(['.content', the_selector].join())