gpt4 book ai didi

javascript - 冲突的脚本......可能

转载 作者:行者123 更新时间:2023-11-29 15:33:14 29 4
gpt4 key购买 nike

关于 my website ,有一段代码可以向页面添加几个元素。这段代码不是我可以编辑的东西,而且我对它放置这些元素的位置不满意,因为它弄乱了我的一些布局。所以我想出了一个小的 jQuery 来将它们移动到一个更理想的位置 - 我希望它们成为其他代码用于其父元素的元素的 sibling 。

$('.mini-profile').after(function() {
var $infection = [$(this).children('.infection_badge'), $(this).children('.infection_button')];
return $infection;
});

我有一个工作 JSFiddle .

问题是当我将这段代码添加到页面时它不起作用。我认为它可能在其他脚本添加元素之前运行,所以我尝试在窗口加载完成时调用它,但这没有用,我不确定还能尝试什么。有没有办法让它工作,或者我是否必须想出另一种方法来解决我的布局问题?

最佳答案

更新

忘记我的其余答案(我会保留它,因为它可以包含对其他人有用的提示)并将您的代码修改为:

$( '.mini-profile' ).after( function() { 
return $( this ).find( '.infection_badge, .infection_button' ) ;
});

我不认为它们是“冲突的”。如果 jQuery 与其他 JS 库发生冲突,就会发生这种情况。而且,正如您可以在 jQuery 的文档中看到的那样:

The jQuery library and virtually all of its plugins are contained within the jQuery namespace. As a general rule, global objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library... (read more)

如果这确实是问题所在(您会知道,因为没有 jQuery 代码会起作用),您可以阅读该文档的其余部分以了解如何避免遇到冲突。

但是,最有可能的是,jQuery 可以工作,而您的问题是当您调用 jQuery 函数时外部脚本没有完成它的工作。

如果您无法编辑其他脚本(并且您确定正确引用了 jQuery 库),您可以尝试以下解决方法:

  1. 监听 $(window).load() 事件:

    它会晚于 $(document).ready() 执行,当所有内容都已加载时。因此,如果其他脚本使用它,则不能使用 $(document).ready() 修改它的工作:

    $(window).load( function() {
    $('.mini-profile').after(function() {
    return [$(this).children('.infection_badge'), $(this).children('.infection_button')];
    });
    });
  2. 设置超时:

    所以你给其他代码执行时间。

    $(document).ready(function() {
    setTimeout(function() {
    $('.mini-profile').after(function() {
    return [$(this).children('.infection_badge'), $(this).children('.infection_button')];
    });
    }, 1000);
    });
  3. 使用 MutationObserver :

    如 MDN 中所定义:

    MutationObserver provides developers a way to react to changes in a DOM

    因此您可以等到其他脚本修改该元素后再进行您自己的修改。

  4. CSS 技巧:

    当然它很乱,但也许您可以仅使用 CSS 来获得所需的结果。例如,转到你的 fiddle ,删除所有 JS 并添加此 CSS:

    .infection_button {
    float: left;
    margin-top: 10px;
    }

    如您所见,它看起来是一样的。我知道它在您的实际布局中会变得更加复杂,但是当其他方法都失败时,仍然可以尝试一下。

希望对您有所帮助!

关于javascript - 冲突的脚本......可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384834/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com