使用自定义自动刷新js代码会产生冲突

时间:2013-09-01 10:37:32

标签: javascript jquery ajax wordpress buddypress

当我开始使用此代码段自动刷新带有ajax的块时,与“非常喜欢”的活动会发生冲突:

myscr.js

jQuery( document ).ready( function() {
    function update() {
      jQuery("#notice").html('Updating...'); 
      jQuery.ajax({
        type: 'GET',
        url: 'http://domain.com/activity',
        data: "recentac=true",
        //timeout: 5000,
        success: function(data) {
          jQuery("#recent-activities").html(data);
          jQuery("#notice").html(''); 
          window.setTimeout(update, 20000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          jQuery("#notice").html('Error in connection');
          window.setTimeout(update, 5000);
        }
    });
    }
    update();
});

我使用wp_enqueue_script打印我的脚本:

function auto_refresh()
{
    wp_enqueue_script('myscr', get_template_directory_uri().'/myscr.js', array("jquery"), '1.0', true );
}
add_action('wp_enqueue_scripts', 'auto_refresh', 99);

自动引用工作,我注意到在自动刷新之前,“喜欢”工作,之后它没有!控制台也没有显示任何错误。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

嘿我不确定这是否会有所帮助,但我已经阅读了一些没有冲突的内容,这就是它在链接下所说的内容,我复制了大部分内容,还有额外的好东西可以在链接上阅读,所以点击它获取更多信息。希望这有帮助

网站链接:http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

将jQuery置于无冲突模式 当您将jQuery置于无冲突模式时,您可以选择分配新的变量名来替换$别名。

<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>

var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.

$j(document).ready(function() {
    $j( "div" ).hide();
});

// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
    var mainDiv = $( "main" );
}

</script>

在上面的代码中,$将恢复到原始库中的含义。您仍然可以在应用程序的其余部分使用完整的函数名jQuery以及新的别名$ j。新的别名可以命名为你喜欢的任何东西:jq,$ J,awesomeQuery等。

最后,如果您不想定义完整jQuery函数名称的另一种替代方法(您真的想使用$而不关心使用其他库的$方法),那么您还可以尝试另一种方法:只需添加$作为传递给jQuery(document).ready()函数的参数。这种情况最常用于您仍然希望获得真正简洁的jQuery代码的好处,但不希望与其他库发生冲突。

    <!-- Another way to put jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>

jQuery.noConflict();

jQuery( document ).ready(function( $ ) {
    // You can use the locally-scoped $ in here as an alias to jQuery.
    $( "div" ).hide();
});

// The $ variable in the global scope has the prototype.js meaning.
window.onload = function(){
    var mainDiv = $( "main" );
}

</script>